How to use pagination along with laravel eloquent

2019-07-23 18:04发布

问题:

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

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$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('App\Post');
    }
}

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.

回答1:

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) !!}



回答2:

With this line $tag = Tag::find($id)->paginate(5); You should get only one tag(or null if tag with your id dose not exist), and after that you want paginate it. If you want paginate your tags get all tags and after that paginate it Tag::paginate(5)