Reputation: 1626
I created a middleware which allows allows users only if they have a role client
.
But when i use the middleware it still let the users to access routes who dont have client role.
public function handle($request, Closure $next)
{
$user = \Auth::user();
if ($user && $user->role = 'client') {
return $next($request);
}
return redirect('home');
}
Here is my route. I did the same thing with other middleware which works fine. but not this
Route::group(['middleware'=>['auth']],function(){
Route::group(['middleware'=>['client']],function(){
Route::get('/index',[
'as' => 'index',
'uses' => 'HomeController@showCandidates',
]);
});
});
When the role is not client it shouldn't let access the route but it does.
edit From alexey's answer I changed my other middleware with == , the question above is solved. But the middleware below restricts me from accessing the route even though my role is interviewer.
public function handle($request, Closure $next)
{
$user = \Auth::user();
if($user && $user->roles == 'interviewer'){
return $next($request);
}
return redirect('home');
}
Here is my route
Route::group(['middleware'=>['auth','interviewer']],function(){
Route::get('/candidates', [
'uses' => 'candidateController@showProfile',
]);
});
What is the possible error i am making here. It works fine when =
is used in interviewer middleware and ==
used in client middleware and not working when done vice versa.
Upvotes: 1
Views: 610
Reputation: 3704
I found a nice convention called Yoda Conditions to avoid such issues in the future.
in your
if ($user && $user->role = 'client') {
return $next($request);
}
Instead doing
$user->role == 'client'
do
'client' == $user->role
The usefulness of this is if you mistakenly type =
instead of ==
, $user->role
doesn't get assigned the value client
. So you could avoid unexpected behaviors.
Read more about To Yoda or Not to Yoda
Upvotes: 3
Reputation: 163758
Since you're checking the role, change this:
$user->role = 'client'
To this:
$user->role == 'client'
Upvotes: 3