Home » Php » php – Laravel Checking If A Collection Contains A Foreign Key

php – Laravel Checking If A Collection Contains A Foreign Key

Posted by: admin July 12, 2020 Leave a comment

Questions:

I was wondering if there is a function or something else, where you can get an other element from a collection than the primary key… For example if votes would have a foreign key ‘user_id’, how do I check this? On the laravel doc there was only an example to check the primary key by using contains(). Can anyone help me out?

Example that checks if there is a vote with id = 2

@foreach($projects as $project)
  @if ($project->votes->contains(2))
  //
  @endif
@endforeach

I would want something to check if there is a vote that has a ‘user_id’ = signed in users id

@foreach($projects as $project)
  @if ($project->votes->contains('user_id' == Auth::id()))
  //
  @endif
@endforeach
How to&Answers:
if ($votes->contains('user_id', auth()->id())) {
    //
}

Answer:

In your model

public static checkForeign($thisId) {
    ( $thisId == Auth::user()->id ) ? return true : return false;
}

In the view

@if ( ModelName::checkForeign($project->votes->id) ) 
    // Do something
@endif