skip to Main Content

I am at the admin user, which is holding the administrator role, but when I add a condition to check if the user is admin or not it will always return false. I can’t find the problem.
This is my code:

So this is my roles table:
enter image description here

And this is my users table:
enter image description here

I set up the relation in my user model, and a condition in the END OF THE CODE which will check if the user is admin or not:

/**
 * The attributes that are mass assignable.
 *
 * @var array<int, string>
 */
protected $fillable = [
    'name',
    'email',
    'password',
];

/**
 * The attributes that should be hidden for serialization.
 *
 * @var array<int, string>
 */
protected $hidden = [
    'password',
    'remember_token',
];

/**
 * The attributes that should be cast.
 *
 * @var array<string, string>
 */
protected $casts = [
    'email_verified_at' => 'datetime',
];

public function role() {
    return $this->belongsTo('AppModelsRole');
}

public function isAdmin() {
    if($this->role->name == 'administrator')
        return true;
    else
        return false;
}

}

Than I created a middleware which will allow me to go in to the admin page if the user is admin else it will redirect me to the root:
enter image description here

Than at the end I added the route with the controller:
enter image description here

And here is the controller in case you need it:
enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    I found my mistake, so I runed:

    return dd(Auth::user()->role->name)
    

    And It rendered this in the page:

    "administrator  "
    

    I had them:

    Auth::user()->role->name == "administrator"
    

    but this means:

    "administrator  " == "administrator"
    

    The problem was that I putted an extra space when I added the role name into my database, be aware of that because its a hard mistake to see.

    BE AWARE OF THE SPACING!

    Now it works!!


  2. first of all the route action should be:

    Route::get('/admin', [AdminController::class, 'index'];
    

    than to check weather user is admin or not you can do it in middleware like this:

    if (auth()->user()->role->name == 'administrator') {
        return $next($request);
    } else {
        return redirect('/');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search