首页 > 解决方案 > 我在 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 不存在。” 在方法“索引”中,分页没有错误。

标签: phplaravellaravel-8tagging

解决方案


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

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

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


推荐阅读