[英]how to show multiple category name from checkbox value in eloquent relationship laravel
首先,我是 laravel 的新手。
我在服务器中插入一个数组数据作为字符串。 列名“category_id”和值如“1,2,3,4”。
现在我只想用 eloquent 关系显示这些 id 的类别名称。 使用 laravel 最新版本。
查看页面
{{$category_var = explode(',',$post->category_id)}}
@foreach($category_var as $category)
@if($category)
<span class="badge mb-3"><a href="#" class="text-white">{{$post->category->category}}</a> </span>
@endif
@endforeach
class页面
public function category(){
return $this-> belongsTo(Category::class);
}
Controller页面
public function index()
{
$posts = post::paginate(9);
return view('pages/home',compact('posts'));
}
还有什么需要问我的。 谢谢
只需使用模型和关系的好处,如下所示:
@foreach($posts as $post)
@foreach($post->category as $category)
<span class="badge mb-3">
<a href="#" class="text-white">{{ $category->(what ever you want from category model) }}</a>
</span>
@endforeach
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.