我在 Laravel 8 中使用 rtconner/laravel-tagging 按标签获取时出错了

问题描述

我尝试通过标签获取帖子。标签有 slug,标签链接应该指向 url 中带有标签 slug 的页面。但是我在该页面上显示带有相关标签的帖子时遇到问题。

邮政控制器。方法 'index' 效果很好,可以显示所有带有相关标签的帖子。在 'fetch' 方法中,我尝试在函数 '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}','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”时,出现错误“Method Illuminate\Database\Eloquent\Collection::paginate does not exist”。在方法 'index' 中,分页没有错误。

解决方法

我认为你应该像这样直接在 paginate 方法上运行 withAnyTag

$posts = Post::withAnyTag([$slug])->paginate(5);

您不需要单独调用 get(),因为 paginate 将运行查询并返回分页结果。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...