I'm using Larave10 Jetstream livewire and I wanna modify the login. But my code doesn't work properly what I thought.
This is user database. Id, name:varchar(255), email:varchar(255), usertype:varchar(255), photo:varchar(255), address:varchar(255)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
class HomeController extends Controller
{
public function redirect() {
$usertype = Auth::user()->usertype;
if($usertype == '1') {
return view('admin.home');
} else {
return view('dashboard');
}
}
}
class RouteServiceProvider extends ServiceProvider
{
public const HOME = '/redirect';
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
}
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
Route::middleware([
'auth:sanctum',
config('jetstream.auth_session'),
'verified',
])->group(function () {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
});
Route::get('/redirect', [HomeController::class, 'redirect']);
Where should I modify ?
You should check RedirectIfAuthenticated.php
First add dashboard
suffix
{
public const HOME = '/home';
public const DASHBOARD = '/dashboard'; // new url aside from HOME
{
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
if (Auth::user()->usertype === 1) {
return redirect(RouteServiceProvider::DASHBOARD); // to dashboard
} else {
return redirect(RouteServiceProvider::HOME); // to home
}
}
}
return $next($request);
}
}
This will redirect to https://localhost/dashboard if usertype === 1 else it will be to https://localhost/home. Redirection happens when you login
This is because of middlelware RedirectIfAuthenticated
was added in app\Http\Kernel.php
protected $routeMiddleware = [
...
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
...
];