I'm using Laravel Breeze + Inertia (React) and want to implement custom auth.
I'm having infinite redirection (ERR_TOO_MANY_REDIRECTS) when visiting /dashboard
on this middleware.
Route::get('register', [RegisteredUserController::class, 'create'])
->name('register');
Route::post('register', [RegisteredUserController::class, 'store']);
Route::get('login', [AuthenticatedSessionController::class, 'create'])
->name('login');
Route::post('login', [AuthenticatedSessionController::class, 'store']);
Route::middleware(['custom_auth'])->group(function () {
Route::get('/dashboard', function () {
return Inertia::render('Dashboard');
})->name('dashboard');
});
class CustomAuthMiddleware
{
public function handle(Request $request, Closure $next)
{
if (session()->has('user_data')) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
}
This works:
namespace App\Http\Middleware;
class RedirectIfAuthenticated
{
public function handle(Request $request, Closure $next, ...$guards)
{
if (session()->has('user_data')) {
return redirect()->route('users.index');
}
return $next($request);
}
}
namespace App\Http\Middleware;
class CustomAuthMiddleware
{
public function handle(Request $request, Closure $next)
{
if (session()->has('user_data')) {
return $next($request);
}
return redirect('login');
}
}
Route::middleware('guest')->group(function () {
Route::get('register', [AuthController::class, 'register'])
->name('register');
Route::post('register', [AuthController::class, 'registerPost']);
Route::get('login', [AuthController::class, 'login'])
->name('login');
Route::post('login', [AuthController::class, 'loginPost']);
});
Route::middleware('custom_auth')->group(function () {
Route::get('/', function () { return redirect()->route('users.index'); });
Route::resource('users', UserController::class);
});
Open your terminal and in your project root folder, type php artisan make:middleware UserData
. "UserData" is the class name of the middleware, it can be any name of your choice.
Open this middleware file; it'll be created in your app/Http/Middleware folder.
public function handle(Request $request, Closure $next)
{
if (session()->has('user_data')) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
After saving, open the Kernel.php file in your app/Http folder and register your middleware in the protected $routeMiddleware array , add this to the last list
'user_data' => \App\Http\Middleware\UserData::class
"user_data" is the name of your middleware, it can be any name of your choice
In the web route
Route::middleware(['user_data'])->group(function () {
Route::get('/dashboard', function () {
return Inertia::render('Dashboard');
})->name('dashboard');
});
I hope you understand. In case of anything I'll be glad to help
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.