Home > database >  Redirection in Authentication Laravel
Redirection in Authentication Laravel

Time:12-24

I´m doing a website, when a normal user log in, it must redirect to a welcome page, if it is an admin user it must redirect to the dashboard. The problem is that only redirect to the welcome page even if it is admin. I am a beginner in laravel and I am not clear about middleware and the routes in laravel 8 so maybe I am missing something. I will add the most important parts of the code.

web.php

  <?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\GasController;

Auth::routes();

Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('welcome');

Route::resource('gasolina', GasolinaController::class);

admin.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\HomeController;

Route::middleware(['auth', 'isAdmin'])->group(function () {
Route::get('/dashboard', [App\Http\Controllers\Admin\HomeController::class, 'index'])->name('admin.index');
});

AdminMiddleware.php

<?php

namespace App\Http\Middleware;
use Closure;
use Auth;
use Illuminate\Http\Request;

class AdminMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        if (Auth::user() && Auth::user()->admin == True)
        return $next($request);

    return redirect('/');
    }
}

LoginController.php

 protected function redirectTo(){
        if (Auth::user()->admin == True){
            return route('admin.index');  // admin path
        } else {
            return route('welcome');  // normal user path
        }
    }

RouteServiceProvider.php

public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
            Route::middleware('web', 'auth')
                ->prefix('admin')
                ->namespace($this->namespace)
                ->group(base_path('routes/admin.php'));
        });
    }

CodePudding user response:

public function showLoginForm()
{
    if(Auth::user() && Auth::user()->admin == True) {
        session()->put('url.intended', 'adminURL');
    }
    return view('auth.login');
}

add this function into your app\Http\Controllers\Auth\LoginController.php

CodePudding user response:

Put this on your LoginController

protected function authenticated(Request $request)
{
  if (Auth::user()->admin == True){
     return route('admin.index');  // admin path
  } else {
     return route('welcome');  // normal user path
  }
}
  • Related