Search code examples
phplaravelpolymorphismrelationship

Laravel 9 laravel associate polymorphic relations bookmarks


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


Solution

  • 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