Reputation: 391
I have a function to check if a user is a Task App Admin
Task Model:
public function isTaskAppAdmin()
{
foreach($this->application->admins as $admin) {
if($admin->id == \Auth::user()->id) {
return true;
}
return false;
}
}
If I dd($this->application->admins)
it will return a collection if my 5 admins.
But if I use this is my blade file it will only return true if the Auth->user() is the first user in the collection. It will return false if I'm logged in as any of the other 4 admins in the collection.
In my blade file:
@if($task->isTaskAppAdmin())
...
@endif
Not sure what I'm doing wrong here?
Upvotes: 0
Views: 1261
Reputation: 8338
You use return
so that breaks your function.
if($admin->id == \Auth::user()->id) {
// do something else but don't return
}
By returning a value you instantly exit the function so that is the reason that only your 1st loop works.
Inside your loop you always return true/false so the 1st iteration for sure will send you out.
A nicer solution and will work for what you are trying to do is to use array functions to search inside your admin collection.
Since you are using collections you can use collection helpers from laravel to search inside your collection without using a foreach
loop
if($this->application->admins->search(\Auth::user()->id)){
return true;
}
Upvotes: 2
Reputation: 521
This always returns on the first loop. Move the return false
down a line.
public function isTaskAppAdmin()
{
foreach($this->application->admins as $admin) {
if($admin->id == \Auth::user()->id) {
return true;
}
}
return false;
}
Upvotes: 1