Reputation: 191
I'm working on a project where user and admin are two different login. I want to redirect user and admin to their respective dashboard pages. I'm not getting how to do this. In database, I created roles column (1 for admin, 2 for user).
I'm not getting how to set send to a different dashboard.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator,Redirect,Response;
Use App\User;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Session;
use Socialite;
class AuthController extends Controller
{
public function index()
{
return view('login');
}
public function registration()
{
return view('registration');
}
public function postLogin(Request $request)
{
request()->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
// return redirect($this->redirectPath());
}
return Redirect::to("login")->withSuccess('Oppes! You have entered invalid credentials');
}
}
Currently on successful login going only same dashboard. I want to change that and send redirection according to roles.
I have created middleware also, but not getting what exact need to do.
<?php
namespace App\Http\Middleware;
use Closure;
Use App\User;
class RoleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->check()) {
$auth = Auth::user()->roles()->first();
switch ($auth->role) {
case 'admin':
return redirect()->route('admin');
break;
case 'user':
return redirect()->route('user');
break;
default:
return redirect()->route('login');
break;
}
}
return $next($request);
}
}
and routing will be following
Route::get('login', 'AuthController@index');
Route::post('post-login', 'AuthController@postLogin');
Upvotes: 1
Views: 2636
Reputation: 3620
First of all, you don't need to create a middleware for redirecting users based on their role.
Just check the role of user after successful login attempt and do your redirect.
public function postLogin(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
// Set redirect route/path based on user role.
$to = $request->user()->role->name === 'admin' ? 'admin' : 'user';
// Redirect user to a named route.
return redirect()->route($to); // or return redirect($to);
}
return Redirect::to('login')->withSuccess('Oops! You have entered invalid credentials.');
}
Upvotes: 1
Reputation: 1334
You can Manage different different dashboards for User and Admin URLs Easily using Gates method also in Laravel.
refer and Try to understand this Example,
Upvotes: 0