Skip to content
Advertisement

How to use pagination along with laravel eloquent find method in laravel 5.4

I am trying to implement pagination in laravel and got following error

Undefined property: IlluminatePaginationLengthAwarePaginator::$name

Here is my controller function

public function showTags($id)
{
    $tag = Tag::find($id)->paginate(5);

    // when lazy loading
    $tag->load(['posts' => function ($q) {
        $q->orderBy('id', 'desc');
    }]);

    return view('blog.showtags')->withTag($tag);
}

Here is the Tag Model

class Tag extends Model
{
    public function posts() 
    {
        return $this->belongsToMany('AppPost');
    }
}

The Tag and Post model has belongsToMany Relationship so there are many posts under the specific tag and my aim is to iterate all posts under the specific tags descending order of post and also to implement pagination in that page.

Here is the code for showtags view

<table class="table">
    <thead>
    <tr>
        <th>#</th>
        <th>Title</th>
        <th>Tags</th>
    </tr>
    </thead>
    <tbody>
    <?php $count = 1; ?>
    @foreach($tag->posts as $post)
        <tr>
            <th>{{ $count++ }}</th>
            <th>{{ $post->title }}</th>
            <th>@foreach($post->tags as $tag)
                    <span class="label label-default">{{ $tag->name }}</span>
                @endforeach
            </th>
        </tr>
    @endforeach
    </tbody>
</table>

//Here is the code i used for pagination in view
<div class="text-center">
    {!! $tag->posts->links() !!}
</div>

If anybody know how to do this please respond. Thanks in advance.

Advertisement

Answer

I solve the problem by using a simple trick. My aim was to paginate all posts under the same tags just like you guys can see in StackOverflow.

The modified controller function is

public function showTags($id)
{
    $tag = Tag::find($id);
    
    // when lazy loading
    $tag->load(['posts' => function ($q) {
        $q->orderBy('id', 'desc')->paginate(10);
    }]);
    
    return view('blog.showtags')->withTag($tag);
}

As you guys see that I move the paginate() function from find to load function which I use before for sorting post by descending order.

Now in view instead of using traditional method {!! $tag->links() !!} for making link of pagination

I use {!! $tag->paginate(10) !!}

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement