Home > Net >  Can't Compare Name Column form Database
Can't Compare Name Column form Database

Time:11-26

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 setted up the relation in my user model, and a condition in the END OF THE CODE witch 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('App\Models\Role');
}

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

}

Than I created a middleware witch 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

CodePudding user response:

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('/');
}

CodePudding user response:

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!!

  • Related