I wanted to add tags to my posts. (laravel blog)
so I created a table with two columns first one was post_id and the second was tag_id and both these columns were foreign keys. now I want to show the tags for each post and I don't know how to get the table information.
this is my migration file
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->unsignedBigInteger('post_id')->index();
$table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
$table->unsignedBigInteger('tag_id')->index();
$table->foreign('tag_id')->references('id')->on('tags')->onUpdate('cascade')->onDelete('cascade');
});
}
so how do I get the table information in my to show them in view? 得到表中的信息,以显示他们的看法?
public function getHomeIndex(){
$posts = Post::orderBy('created_at', 'desc')->paginate(9);
$tags = ??????
return view('blog.index', ['posts' => $posts], 'tags' => $tags);
}
or maybe I'm doing it wrong and there is a better way to send the tags in veiw?
In Post model define tag
relation
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tag');
}
In controller use
public function getHomeIndex()
{
$posts = Post::orderBy('created_at', 'desc')->with('tags')->paginate(9);
return view('blog.index', ['posts' => $posts]);
}
In view
@foreach($posts as $post)
// post data here
@foreach($post->tags as $tag)
// $tag related data here
@endforeach
@endforeach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.