I have this Bookmark
model
public function bookmarkable()
{
return $this->morphTo();
}
public function user()
{
return $this->belongsTo(User::class);
}
and in my User
model
public function bookmarks()
{
return $this->hasMany(Bookmark::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
and the Post
model
public function bookmarks()
{
return $this->morphMany(Bookmark::class, 'bookmarkable');
}
public function user()
{
return $this->belongsTo(User::class);
}
I want to create a new $bookmark
and associate a $post
with that bookmark
the bookmarks table has the columns bookmarkable_type
, bookmarkable_id
and user_id
My Answer:
morphTo();_}_And I have other models like Article, Video, and Image that can be bookmarked. How can I associate these models with the Bookmark model using polymorphic relations in Laravel 9?
To associate the Article, Video, and Image models with the Bookmark model using polymorphic relations in Laravel 9, you can follow these steps:
1. Define the morphMany relationship in the Article, Video, and Image models:
In the Article model:
php
public function bookmarks()
{
return $this->morphMany(Bookmark::class, 'bookmarkable');
}
In the Video model:
php
public function bookmarks()
{
return $this->morphMany(Bookmark::class, 'bookmarkable');
}
In the Image model:
php
public function bookmarks()
{
return $this->morphMany(Bookmark::class, 'bookmarkable');
}
2. Define the inverse of the morphMany relationship in the Bookmark model:
php
public function bookmarkable()
{
return $this->morphTo();
}
3. Now you can create a new bookmark for an Article, Video, or Image instance:
php
$article = Article::find(1);
$bookmark = new Bookmark();
$article->bookmarks()->save($bookmark);
$video = Video::find(1);
$bookmark = new Bookmark();
$video->bookmarks()->save($bookmark);
$image = Image::find(1);
$bookmark = new Bookmark();
$image->bookmarks()->save($bookmark);
4. You can also retrieve the bookmarks for an Article, Video, or Image instance:
php
$article = Article::find(1);
$bookmarks = $article->bookmarks;
$video = Video::find(1);
$bookmarks = $video->bookmarks;
$image = Image::find(1);
$bookmarks = $image->bookmarks;
By following these steps, you can associate the Article, Video, and Image models with the Bookmark model using polymorphic relations in Laravel 9.
Rate this post
3 of 5 based on 8343 votesComments