i want to let users that have bookmarks. it means users can bookmark posts, articles, etc... so this is my schema users id bookmarks id bookmarkable_id bookmarkable_type user_id articles id posts id as you can see it is a Polymorphic relation.
well i can add a bookmark for an article and it is okay. my problem is when i want to get bookmarks of a user. imagine user have 4 posts that bookmarked. he wants to see them.
i wrote a relation for it but it returns []; ( user at least has one bookmarked post)
User.php
public function bookmarks()
{
return $this->morphMany(Bookmark::class, 'bookmarks', 'bookmarkable_type','user_id');
}
it is the result
Illuminate\Database\Eloquent\Collection {#313 ▼
#items: []
}
and this is Bookmark model:
public function bookmarkable()
{
return $this->morphTo();
}
public function articles()
{
return $this->belongsTo(Article::class ,'bookmarkable_id','id');
}
and this is how i try to access the bookmarks:
$articles = auth()->user()->bookmarks;
dd($articles);
when i use this for get the bookmarked posts:
public function bookmarks()
{
return $this->hasOne(Bookmark::class, 'user_id','id');
}
it will return the record in the bookmarks table.