The laravel first() method is pretty straight forward and that's why this question might be silly, but I am not understanding the use of first() method.
Actually, I'm following a youtube tutorial where I am authenticating a user if he has the role of admin then only he will get the access of route otherwise will be redirected to home.
There is no error or issue with code but my understanding.
I am returning the user in User model class function if the user has the role passed by the middleware
Route
Route::get('admin', function (){
return 'This is Admin page';
})->middleware(['auth', 'auth.admin']);
Middleware
public function handle($request, Closure $next)
{
if (Auth::user()->hasAnyRole('admin'))
{
return $next($request);
}
return redirect('home');
}
User Modal
public function hasAnyRole($role)
{
return null !== $this->roles()->where('name', $role)->first();
}
If I use first() method in hasAnyRole function then only route is protected by other users and only admin get access to the route,
If I remove the first() method then all the users get access to route which I don't understand why?