如何在laravel 5.4中使用分页以及laravel雄辩的查找方法 [英] How to use pagination along with laravel eloquent find method in laravel 5.4

查看:78
本文介绍了如何在laravel 5.4中使用分页以及laravel雄辩的查找方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在laravel中实现分页并出现以下错误

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

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$name

这是我的控制器功能

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

这是标记模型

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

标记和发布"模型具有"ToyToMany Relationship",因此在特定标记下有许多帖子,我的目的是迭代特定标签下的所有帖子(从降序排列),并在该页面中实现分页.

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.

这是showtags视图的代码

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.

推荐答案

我通过一个简单的技巧解决了这个问题.我的目标是将所有帖子都用相同的标签分页,就像你们在StackOverflow中看到的一样.

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.

修改后的控制器功能为

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

你们看到我将paginate()函数从find移到load函数,该函数以前用于按降序对post进行排序.

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.

现在可见,而不是使用传统方法{!! $tag->links() !!}进行分页链接

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

我使用{!! $tag->paginate(10) !!}

这篇关于如何在laravel 5.4中使用分页以及laravel雄辩的查找方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆