Laravel 方法Illumb\Database\Eloquent\Collection
我想在blade中使用分页显示文章,但出现以下错误。 如果不使用分页,我没有问题 BadMethodCallException方法 Illumb\Database\Eloquent\Collection::链接不存在。(观点: c:\xampp\htdocs\blog\resources\views\frontend\tag.blade.php)Laravel 方法Illumb\Database\Eloquent\Collection,laravel,Laravel,我想在blade中使用分页显示文章,但出现以下错误。 如果不使用分页,我没有问题 BadMethodCallException方法 Illumb\Database\Eloquent\Collection::链接不存在。(观点: c:\xampp\htdocs\blog\resources\views\frontend\tag.blade.php) 公共功能标签($slug) { $tag=tag::where('slug',$slug)->first()??中止(404); $articles
公共功能标签($slug)
{
$tag=tag::where('slug',$slug)->first()??中止(404);
$articles=Article::where('status','=','1')->paginate(5);
$article=$tag->articles;
返回视图('frontend.tag',压缩('article');
}
frontend/tag.blade.php:
{{$article->links()}
模型:Article.php
公共职能条款()
{
返回$this->belongtomany(Article::class);
}
您的呼叫不正确。在你的刀片中应该是$article->links()
而不是article->links()
。你在article
中错过了$
{{ $article->links() }}
同样在控制器中删除$article=$tag->articles代码>。因为这将替换第一次查询的分页结果,并且应该
$articles = Article::whereHas('tags',function($query)use($slug){$query->where('slug', $slug)})->where('status', '=', '1')->paginate(5);
最终的解决办法是
public function tag($slug)
{
$articles = Article::whereHas('tags',function($query)use($slug){
$query->where('slug', $slug)})->where('status', '=', '1')->paginate(5);
return view('frontend.tag', compact('article'));
}
文中模型添加关系
public function tags()
{
return $this->belongsToMany(Tag::class);
}
和视图进行分页
{{ $article->links() }}
在刀片文件中,您正在执行{{{article->links()}}
。因此,您将$article
变量用作集合
但是,在控制器中(刀片之前的代码),$articles
是具有分页的变量
您只能在分页器上调用..->links()
(在您的情况下,这是$articles
变量)。不能对集合调用..->links()
(在您的情况下,$article
是一个集合--$tag->articles
的集合)
更新:我假设您没有错过{{article->links()}
中article
变量的$
。否则,您应该会收到一种不同类型的叫喊(解析错误)代码$article=$tag->articles;显示与特定标记相关的文章。公共函数articles(){return$this->belongtomany(Article::class);}更新了我的答案此代码有效。但不显示分页此代码{{$article->links()}}在我的文件中,但不显示分页如何显示控制器和刀片的完整代码;显示与特定标记相关的文章。公共函数articles(){return$this->belongToMany(Article::class);}您的意图不清楚。在frontend/tag.blade.php
中,要显示状态为status=1
的文章的分页链接,还是要显示标记为slug=$slug
和status=1
的文章的分页链接?可以调用集合$articles->links()
上的方法链接,不在单个对象上。