Home > Blockchain >  Laravel 9 laravel associate polymorphic relations bookmarks
Laravel 9 laravel associate polymorphic relations bookmarks

Time:08-04

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

CodePudding user response:

Cause morphTo extends belongsTo

U can use like this

$post = Post::first()// the post u want add to bookmark
$newBookmark = new Bookmark([]);
$newBookmark->name="lorem ipsum";
$newBookmark->bookmarkable()->associate($post);
$newBookmark->user()->associate($post->user);
$newBookmark->save();

See the class docs: https://laravel.com/api/9.x/Illuminate/Database/Eloquent/Relations/MorphTo.html

  • Related