My port server is my login interface. * http://127.0.0.1:8000/* That is my login part, after entering my details it will redirect me to my dashboard http://127.0.0.1:8000/dashboard. But if I remove the /dashboard from the url it returns me back to login even when I am still in session and hasn’t yet click the logout button. If I put the /dashboard again I will return to the dashboard because the user is still in session. I want to return to dashboard even I remove /dashboard. How to do that in Laravel?
Advertisement
Answer
- Middleware can do this work for you. just follow
- Firstly, you have to create a middleware.
php artisan make:middleware RedirectIfUserAuthenticated
- Register your middleware at kernel:
protected $routeMiddleware = [ .............................. 'auth.backend' => MiddlewareRedirectIfUserAuthenticated::class, ];
- Call your middleware at your routes or controller which you want to user authenticated can see after they’re login.
Route::group(['middleware' => ['auth.backend'], function () { // Add your routes except login route. }]);
- Let’s added some codes into middleware that we have created:
RedirectIfUserAuthenticated
<?php namespace AppHttpMiddleware; use Closure; use IlluminateSupportFacadesAuth; class RedirectIfUserAuthenticated { /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $next * @param string|null $guard * @return mixed */ public function handle($request, Closure $next, $guard = null) { if (auth()->check()) { return redirect()->to('/dashboard'); } return $next($request); } }
- Important: You can added middlware
auth
to your routes this will work as well if you don’t want to create new one: Locat at: Middlewares/Authenticat.php and custom whatever your want.
Route::group(['middleware' => ['auth'], function () { // Add your routes except login route. }]);
Done !