Loyd
1 month ago
398
6
Laravel

Check if a morphMany relationship contains $post->id

Posted 1 month ago by Loyd

Hi Devs.

I recently changed my relationship to polymorphic.

I have a likes table & Model that has morphTo

	   $table->id();
            $table->unsignedBigInteger('user_id'); 
            $table->unsignedBigInteger('likeable_id');
            $table->string('likeable_type');
            $table->timestamps();
public function likeable()
    {
    	return $this->morphTo();
    }

& and posts table & Model that has morphMany

public function likes()
    {
    	return $this->morphMany(Like::class, 'likeable');
    }

Before changing to polymorphic I would do something like this

$liked = (auth()->user()) ? auth()->user()->likes->contains($post->id) : false;

to check if auth user likes a certain post. My question is now that I have morphs how do I check this status?

Please sign in or create an account to participate in this conversation.