I have been having problems for a few days regarding access to routes defined for my middlewares. The specific problem with all this is that when, for example, I want to enter a URL of my entity other than Users, it always returns me to the home page, regardless of the user role that the logged-in user has. I leave important parts of the code here in case someone knows why it could be:
Model of Users:
<?php
namespace AppModels;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name',
'email',
'password',
'rol_usuario',
'fecha_nacimiento',
'sexo',
'tarjeta_credito',
];
protected $hidden = [
'password',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Login function in UsuariosController:
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
Log::info('Inicio de sesión exitoso para el email: ' . $request->input('email'));
return redirect()->route('home');
}
return back()->withErrors([
'email' => 'Las credenciales son incorrectas.',
])->onlyInput('email');
}
Middleware for administrators:
public function handle($request, Closure $next) : Response
{
if (!Auth::check()) {
return redirect()->route('login.form')->withErrors('Debes iniciar sesión para acceder a esta página.');
}
if (Auth::user()->rol_usuario !== 'administrador') {
return redirect()->route('home')->withErrors('No tienes permiso para acceder a esta página.');
}
return $next($request);
}
web.php:
// Rutas de autenticación de usuarios
Route::get('login', [UsuariosController ::class, 'create'])->name('login');
Route::post('login', [UsuariosController::class, 'store']);
Route::post('logout', [UsuariosController::class, 'destroy'])->name('logout');
// Rutas para la gestión de carteras
Route::middleware(['auth', 'administrador'])->group(function () {
Route::get('carteras', [CarteraController::class, 'index'])->name('carteras.index');
Route::get('carteras/create', [CarteraController::class, 'create'])->name('carteras.create');
Route::post('carteras/create', [CarteraController::class, 'store'])->name('carteras.store');
});
I have tried to introduce the user_role attribute to the $credentials variable but it does not take it in any way, for the urls of the Users entity I have no problem accessing it, but for Portfolio only the index of the methods created in its controller is accessible.
Carlos Gutiérrez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.