How to get instance of a collection in Laravel 8 to use in a if statement?

Tags: , , ,



How to get instance of a collection in Laravel 8?

I want to make a if statement if $event->like (CODE BELOW) does not exists for that specific event and an else statement I want to execute the below 2nd foreach.

Controller

    $events = Event::select('id', 'name', 'image', 'description', 'datetime', 'description', 'is_published')
        ->with('like:id,id_event,id_user,is_liked,created_at')
        ->with('like.user:id,name,surname')
        ->where('is_published', 1)
        ->paginate(6);

View

@foreach($events as $event)

//DATA

//here I want to implement a if statement if $event->like does not exists for that specific event 
//and else I want to execute the below foreach 

     @foreach($event->like as $like )

       //DATA2

     @endforeach

@endforeach

Answer

if I understand you correctly you will need to check for the likes count if there are likes so iterate throw it like this

@foreach($events as $event)
     @if($event->like->count())

         @foreach($event->like as $like)

            //DATA2

         @endforeach
     @endif
@endforeach


Source: stackoverflow