Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Checking If A Collection Contains A Foreign Key

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
like image 324
Kim Janssens Avatar asked Dec 01 '14 23:12

Kim Janssens


2 Answers

if ($votes->contains('user_id', auth()->id())) {
    //
}
like image 61
Joseph Silber Avatar answered Oct 03 '22 14:10

Joseph Silber


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
like image 36
Rafael Avatar answered Oct 03 '22 16:10

Rafael