php - 我在 Laravel 8 中使用 rtconner/laravel-tagging 按标签获取有问题
问题描述
我试图通过标签获取帖子。标签有标签,标签链接应该指向url中带有标签标签的页面。但是我在该页面上显示带有相关标签的帖子时遇到问题。
后控制器。方法“索引”效果很好,显示所有带有相关标签的帖子。在“获取”方法中,我试图在函数“withAnyTag”中使用它,如文档中所述 — https://github.com/rtconner/laravel-tagging/
public function index()
{
$posts = Post::orderBy('created_at', 'desc')->paginate(5);
return view('backend.post.index', compact('posts'));
}
public function fetch(Tag $tag)
{
$slug = $tag->slug;
$posts = Post::withAnyTag([$slug])->get()->paginate(5);
return view('backend.post.index', compact('posts'));
}
在 Post 模型中没有什么特别的,只是 trait Taggable。
路线。我看他们没有问题,带上它以防万一。
Route::get('post', [PostController::class, 'index'])->name('posts');
Route::get('post/tag/{tag:slug}', [PostController::class, 'fetch'])->name('posts.fetch');
视图'backend.post.index'的片段,用于两种方法。链接运作良好,并引导到正确的网址。
@foreach($posts as $post)
<tr>
<td>{!! $post->title !!}</td>
<td>{!! $post->content !!}</td>
<td>
@foreach($post->tags as $tag)
<a href="{{ route('posts.fetch', $tag->slug) }}">{!! $tag->name !!}</a>
@endforeach
</td>
<td>
<a href="/" class="btn btn-sm btn-outline-primary py-0">Read Post</a>
<a href="{{ route('post.edit', $post->slug) }}" class="btn btn-sm btn-outline-success py-0">Edit Post</a>
<form action="{{route('post.destroy', $post->slug)}}" method="POST">
@method('DELETE')
@csrf
<button type="submit" class="btn btn-sm btn-outline-danger py-0">Delete</button>
</form>
</td>
</tr>
@endforeach
{!! $posts->links() !!}
但是,当我单击标签并进入页面“.../post/tag/tag-slug”时,出现错误“方法 Illuminate\Database\Eloquent\Collection::paginate 不存在。” 在方法“索引”中,分页没有错误。
解决方案
我认为您应该paginate
直接在这样的withAnyTag
方法上运行
$posts = Post::withAnyTag([$slug])->paginate(5);
您不需要单独调用get()
aspaginate
将运行查询并返回分页结果。
推荐阅读
- r - postgresqlNewConnection(drv, ...) 中的错误:用户参数不能为 NULL
- reactjs - Redux action creator 完成,更新订阅的组件
- javascript - 刷子的d3事件传播
- angular - 检测应用打开的次数
- d3.js - 缩放到某个域?
- rx-swift - 如何在 UITableView 的 RXswift 和 RXCocoa 中实现 tableview 单元格的内部?
- javascript - 为 createElement 创建接受更多参数的函数
- javascript - 添加外部 js 文件的最佳和最快方法:追加或使用 $.getscript()?
- javascript - Apexchart 工具提示
- angular - 在Angular 6中单击按钮时无法传递函数的值