[英]get posts by their tags in laravel
I am showing each post tags in my blade now I want make some sort of search for my tags, (take image below as sample) 我现在要在刀片中显示每个帖子标签,我想对我的标签进行某种搜索(以下面的图片为示例)
I want when users clicks on laravel
tag result of every post with laravel tag show to them. 我希望当用户点击
laravel
每一个岗位有laravel标签展示给他们的标签结果。
posts model
public function tags(){
return $this->belongsToMany(Tag::class);
}
tags model
public function posts(){
return $this->belongsToMany(Post::class);
}
Try something like this: 尝试这样的事情:
Post::whereHas('tags', function($query) use ($tag) {
$query->where('title', $tag);
})->get();
Where $tag
would be your tag title. 其中
$tag
是您的标签标题。
Reference: https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-existence 参考: https : //laravel.com/docs/5.6/eloquent-relationships#querying-relationship-existence
Route model binding example from within RouteServiceProvider
: 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();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.