senty
senty

Reputation: 12847

Return if the related model has a value or not as a new field

I have Post model and related Likes item. I am trying to return the if the related model has a row for authenticated user or not. So the tables look like:

Posts
- id
- body
- etc

Likes
- id
- user_id
- likable_type
- likeable_id

Now I am return Posts eloquent with Posts::get(), however I want to return every model with a parameter inside is_liked which shows if the authenticated user has liked that post or not.

If I use ->with('likes')->where(function($q)) {} approach, it will only return me the Post that user has liked but this is not what I want.

I want every Post object to show if the authenticated user has liked it or not. Such as: Post { id, body, is_liked }

Is there any way of achieving this beside running a for loop? What is the best way to handle such scenario?


Update

class Post extends Model {
       protected $appends = ['is_liked'];

       public function getIsLikedAttribute() {
          return $this->has('likes.user_id', '=', Auth::id())->exists();
       }

      public function likes() {
        return $this->morphOne('App\Like', 'likeable');
      }
}

class Like extends Model {
   protected $fillable = [
      'user_id', 'likeable_id', 'likeable_type'
   ];

   public function likeable() {
      return $this->morphTo();
   }
}

Writing through this morph works, however, $this->has('likes.user_id' part returns error

Method Illuminate\Database\Query\Builder::user_id does not exist.

Upvotes: 0

Views: 105

Answers (1)

Asur
Asur

Reputation: 4017

You can use am accessor and add that property to the append protected variable:

protected $appends = ['is_liked']; 

public function getIsLikedAttribute() { 
   return $this->likes()->where('user_id',  '=',  Auth::id())->exists();
}

Now you can also check the accessor like

$post->is_liked // bool

Upvotes: 1

Related Questions