通过laravel中的标签获取帖子

时间:2018-06-05 00:44:28

标签: php laravel

我正在我的刀片中显示每个帖子标签现在我想对我的标签进行某种搜索,(以下面的图片作为样本)

screen 1

我希望当用户点击每个帖子的laravel标记结果时,会显示laravel标记。

问题

  1. 我该如何制作这个功能?
  2. 代码

    posts model

    public function tags(){
       return $this->belongsToMany(Tag::class);
    }
    

    tags model

    public function posts(){
       return $this->belongsToMany(Post::class);
    }
    

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

Post::whereHas('tags', function($query) use ($tag) {
    $query->where('title', $tag);
})->get();

$tag将成为您的标记标题。

参考:https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-existence

RouteServiceProvider内部路由模型绑定示例:

public function boot()
{
    parent::boot();

    Route::patterns([
        'tag_title' => '[a-z]+',
    ]);

    Route::get('posts/{tag_title}', function ($tag_title) {
        return Tag::where('title', $tag_title)->firstOrFail();
    });
}