Check ID with a single foreach

Asked

Viewed 68 times

-1

I wonder if you have a certain id, without having to do two foreach

  @forelse($surveys as $survey)
          @forelse($survey->users as $user)
               @if($user->id == $auth()->user())
                    AÇÃO
           @empty
           @endfor
  @empty
  @endfor

I have a table N pra N of survey and user. would like a solution of the kind

 @if($survey->users->contains('id',auth()->user()->id))

But I did not get results, I check it in blade, someone has a solution?

  • 1

    You cannot mount a select to return only the data that fits in these cases?

2 answers

0

Yes has a solution, creates the method contains there in Survey, example:

//survey

public function contains($column = 'id', $value = 0)
{
    $users = $this->users;
    foreach($users as $user) 
    {
        //existe algum user com $column, $value ?
        if($user->{$column} === $value) 
        {
            return true;
        }
    }

    return false;
}

In Blade it would be something like

$survey->contains('id',auth()->user()->id)

0

Friend, I think you’re thinking the other way around. You want to get the logged in user’s Surveys not? Use Azy eagerload.

$user = \Auth::user();
$user->load('surveys');

foreach($user->surveys as $survey)...

That way you don’t need to use the Collection’s 'contains' method.

Reference: https://laravel.com/docs/5.8/eloquent-relationships#Lazy-Eager-loading

Browser other questions tagged

You are not signed in. Login or sign up in order to post.