I'm trying to get all the users where a given method in User
model meets. Please see my code below:
User.php
public function isPicker(){
return ($this->where('isPicker', 1)) ? true : false;
}
Now, I can use User::all();
, but it returns all the users. What I want is to only return the users that meets the isPicker()
method. What I'm trying to do in view is:
@foreach($users as $user)
@if($user->isPicker())
{{ $user->first_name }}
@endif
@endforeach
This is also working fine, but it is not that efficient to use. What if there's a lot of method to check? Any idea for this?
Just do:
$users = User::where('isPicker', 1)->get();
Or create a scope:
public function scopeIsPicker($query)
{
return $query->where('isPicker', 1);
}
// usage
$users = User::isPicker()->get();
Well you could change you code up a little to look like this.
@foreach($users->where('isPicker', 1)->all() as $user)
{{ $user->first_name }}
@endforeach
But this will only work if the users var is a collection.
Other wise just change you query on how your getting the users to something like this.
User::where('isPicker', 1)->get()
Instead of checking in model file, you can directly query in your controller try below code
Controller Code :
$users = User::where('isPicker', 1)->get();
Blade code :
@foreach($users as $user)
{{ $user->first_name }}
@endforeach
OR
Controller Code :
$users = User::all();
Blade code :
@foreach($users as $user)
@if($user->isPicker == 1)
{{ $user->first_name }}
@else
<p>Picker is 0</p>
@endif
@endforeach
Note : Remove your isPicker function from user model file because its unuse.