I'm trying to use middlewares to protect Routes based on role.

Im testing with this route to allow only the role `administrador` to be able to enter it.

```
Route::get('/gestionarMedicos', [PersonaController::class,'mostrarMedicos'])->name('personaMostrarMedicos')->middleware('auth','firstLogin','role:administrador');

```

This is code of my middleware (in the route its the one called route)

```
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class EnsureUserHasRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $role)
    {

        if (! $request->user()->hasRole($role)) {
            // Redirect...
            return back();
        }
        return $next($request);

    }
}

```

This is the code of the User model

```
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = [
        'role',
        'name',
        'email',
        'password',
        'idPersona',
        'estado'
    ];

    public function Persona(){
        return $this->belongsTo(Persona::class,'idPersona');
    }
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'remember_token'
    ];

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

    public function hasRole($role)
    {
        return User::where('role', $role)->get();
    }
}

```

Some logic is not done right because I can access the Route even with users that doesn't have that role

The dd() in the middleware was for testing, I get "administrador" with it.

I have tried Patrick Obafemi solution but I still have the same problem.

For testing I did a dd of what the if based on Patrcik answer result is and it is false.

I'm not sure where is the logic problem.

[![Value of condition false](https://i.stack.imgur.com/MEwX7.png)](https://i.stack.imgur.com/MEwX7.png)

I'm also going to post a picture of my database model if it helps in some way.

[![Database model](https://i.stack.imgur.com/TmJKH.png)](https://i.stack.imgur.com/TmJKH.png)