Frank Provost Frank Provost - 1 month ago 7
PHP Question

Eloquent return amount of relation AND a bool if the user has the relation aswell

I have a model for "novels" which are "bookmarkable" and have "bookmarks"

I would like to show the amount of bookmarks a novel has and to determine if the currently logged in user bookmarked the novel.

App\Novel::withCount('chapters', 'bookmarks')
->with(['author', 'ratings'])
->newestPublished()
->paginate(10)


This shown call works perfectly fine. However i'd love to see directly on the result if the current user has bookmarked the novel.

For the count of the bookmarks i built the following into my novel Model

public function getBookmarksCountAttribute()
{
return $this->bookmarks()->count();
}


Can I somehow create ANOTHER "getBookmarksCountAttribute" method which then works like this

public function getUserBookmarkCountAttribute()
{
if ( !Auth::user() ) {
return false;
}

return $this->bookmarks()->where('user_id', Auth::user()->id)->first() ? true : false;
}


Is there a way to easily add this to my query?

Answer

The method first() results the first result or null.

Solution

public function getUserBookmarkCountAttribute()
{
    if ( !Auth::user() ) {
        return false;
    }

    return !is_null($this->bookmarks()->where('user_id', Auth::user()->id)->first());
}

Alternative Solution

public function getUserBookmarkCountAttribute()
{
    if ( !Auth::user() ) {
        return false;
    }

    return $this->bookmarks()->where('user_id', Auth::user()->id)->first() instanceof Bookmark;
}

Tip 1

You can add the attribute to the $appends array, so you don't need to store the count in your table explicitly.

Tip 2

Using the Auth facade in your model is not a good practice. Better is to pass the user object / id to the model with Dependency Injection.

Comments