Created
March 28, 2019 00:23
-
-
Save kenmasters/6d2009b4c2a9d89327be27cb678b3512 to your computer and use it in GitHub Desktop.
Laravel5.7 Login Redirect base from User Role(Spatie/Laravel-Permission package)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers\Auth; | |
use App\Http\Controllers\Controller; | |
use Illuminate\Foundation\Auth\AuthenticatesUsers; | |
use Illuminate\Http\Request; | |
class LoginController extends Controller | |
{ | |
/* | |
|-------------------------------------------------------------------------- | |
| Login Controller | |
|-------------------------------------------------------------------------- | |
| | |
| This controller handles authenticating users for the application and | |
| redirecting them to your home screen. The controller uses a trait | |
| to conveniently provide its functionality to your applications. | |
| | |
*/ | |
use AuthenticatesUsers; | |
/** | |
* Create a new controller instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
$this->middleware('guest')->except('logout'); | |
} | |
/** This method handles redirection base from a given role after a user is authenticated */ | |
protected function authenticated(Request $request, $user) | |
{ | |
if ($user->hasRole('Admin')) { | |
return redirect('admin/dashboard'); | |
exit(0); | |
} elseif ($user->hasRole('Tenant')) { | |
return redirect('tenant/dashboard'); | |
exit(0); | |
} | |
return redirect(route('user.index')); | |
exit(0); | |
} | |
/** This method enables a user loggedin using email or username. | |
For authenticating using `username` there must be a username column in the users table. | |
*/ | |
public function username() | |
{ | |
$login = request()->input('log'); | |
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username'; | |
request()->merge([$field => $login]); | |
return $field; | |
} | |
/** This method overrides the validation for login fields. | |
Since we change the `name=password` field to `name=pwd` in the login form. | |
We need to override this method from `AuthenticatesUsers` trait for the validation to work properly. | |
*/ | |
protected function validateLogin(Request $request) | |
{ | |
$request->validate([ | |
$this->username() => 'required|string', | |
'pwd' => 'required|string', | |
]); | |
request()->merge(['password' => $request->input('pwd')]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment