How can I add DESC to the default login sql query?
I mean on default is something like
select * from users where name = user_name limit 1.
How can I add
select * from users where name = user_name ORDER BY id DESC limit 1?
I know that the name column should contain unique values only, my login system it's different (some predefined users in another table) and I need multiple user registrations with the same name. I just want to login on the last record in the database. Please help me how can I customize the model provider in laravel? I don't know what files to modify for this to work.
This is my LoginController.php but you can ignore it (I added it because some users required it) just look at the default loginController from php artisan make:auth
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Session;
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;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Check either username or email.
* #return string
*/
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
public function username()
{
$identity = Session::get('table_id');
$fieldName = 'name';
request()->merge([$fieldName => $identity]);
return $fieldName;
}
/**
* Validate the user login.
* #param Request $request
*/
protected function validateLogin(Request $request)
{
$this->validate(
$request,
[
'password' => 'required|string',
],
[
'password.required' => 'Password is required',
]
);
}
/**
* #param Request $request
* #throws ValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
$request->session()->put('login_error', trans('auth.failed'));
throw ValidationException::withMessages(
[
'error' => [trans('auth.failed')],
]
);
}
protected function attemptLogin(Request $request)
{
$remember = true;
return $this->guard()->attempt(
$this->credentials($request), $remember
);
}
}
All methods in my LoginController overrides methods from vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
Replace LoginController with the following. I have removed username() method and replaced attemptLogin() method to fetch the last user in your database given your session value of 'table_id'.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Session;
use App\User;
use Illuminate\Support\Facades\Auth;
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;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->middleware('guest')->except('logout');
$this->user = $user;
}
/**
* Check either username or email.
* #return string
*/
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
/**
* Validate the user login.
* #param Request $request
*/
protected function validateLogin(Request $request)
{
$this->validate(
$request,
[
'password' => 'required|string',
],
[
'password.required' => 'Password is required',
]
);
}
/**
* #param Request $request
* #throws ValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
$request->session()->put('login_error', trans('auth.failed'));
throw ValidationException::withMessages(
[
'error' => [trans('auth.failed')],
]
);
}
protected function attemptLogin(Request $request, User $user)
{
if (session()->has('table_id') != true) return redirect()->back()->withErrors(['error' => 'No username is set.']);
$userName = $user->where('name', session('table_id'))->orderBy('id', 'desc')->first()->name;
$remember = true;
if (Auth::attempt(['name' => $userName, 'password' => request('password')], $remember)) {
return redirect()->intended();
}
}
}
You should not change/delete any framework files and codes.
in top of your login controller just add this trait:
use AuthenticatesUsers;
then you can override all login functions.
for authenticating username/password just override attemptLogin() function.
So if I understand your question right, you want to change default sql query for selecting user when authenticating.
in attemptLogin method you call attempt and it is in StatefulGuard Interface and the implementation is in /vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php so you need to either override full attempt method, either the methods in it.
I found another solution that works but I believe it will mess something up (I'm not sure) that is why I voted Polaris's answer as the right one.
You can leave the default LoginController and modify the App/User.php like this:
It basically overrides the retrieveByCredentials method used in Illuminate\Auth\EloquentUserProvider; . The issue is that I believe this method is not normally accessed directly from the Users.php so you are not directly overriding it. But for some reason it works :)).
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Auth\EloquentUserProvider;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials) ||
(count($credentials) === 1 &&
array_key_exists('password', $credentials))) {
return;
}
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if (Str::contains($key, 'password')) {
continue;
}
if (is_array($value) || $value instanceof Arrayable) {
$query->whereIn($key, $value);
} else {
$query->where($key, $value);
}
}
return $query->orderBy('id', 'desc')->first();
}
}
Related
I am trying to make authentication with ActiveDirectory using ldaprecord-laravel. I followed the documentation and made required changes in files. However, I ended up with only php artisan ldap:test working and php artisan ldap:import ldap showing that there are no users to import.
When I use online LDAP test server, I can go further and make Auth::attempt(['uid' => 'einstein', 'password' => 'password']) in Tinker, and import works, but the web login still doesn't work. With AD, I can't auth attempt using neither samaccountname, nor username, nor uid. Though plain auth using ldap_connect and ldap_bind works.
App/User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use LdapRecord\Laravel\Auth\LdapAuthenticatable;
use LdapRecord\Laravel\Auth\AuthenticatesWithLdap;
class User extends Authenticatable implements LdapAuthenticatable
{
use Notifiable, AuthenticatesWithLdap;
protected $table = 'users';
protected $primaryKey = 'id';
public $timestamps = false;
public $incrementing = false;
/*
public function getAuthPassword()
{
return Hash::make( $this->user_pass );
}
*/
/**
* Настройки пользователя.
*
* #return HasMany
*/
public function settings()
{
return $this->hasMany(Models\Settings::class, 'id', 'id');
}
}
App/Http/Controllers/Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use LdapRecord\Laravel\Auth\ListensForLdapBindFailure;
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, ListensForLdapBindFailure;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Переопределяем переменную, в которой хранится логин пользователя
*
* #return string
*/
public function username()
{
return 'user_login';
}
/**
* Валидация данных на сервере
*
* #param Request $request
*
* #return void
*/
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
protected function credentials(Request $request)
{
return [
'uid' => $request->username,
'password' => $request->password,
];
}
}
How can I find out what causes the problem?
Troubleshooting in Laravel is usually done with logging. According to the given document, you may log string using
use Illuminate\Support\Facades\Log;
// somewhere in the code
Log::debug('info string');
Laravel puts it's logs in storage/logs folder. There are such entries in the log:
[2021-08-24 10:41:13] local.INFO: LDAP (ldap://ldap.forumsys.com:389) - Operation: Bound - Username: cn=read-only-admin,dc=example,dc=com
[2021-08-24 10:35:54] local.INFO: LDAP (ldap://ldap.forumsys.com:389) - Operation: Search - Base DN: dc=example,dc=com - Filter: (&(objectclass=\74\6f\70)(objectclass=\70\65\72\73\6f\6e)(objectclass=\6f\72\67\61\6e\69\7a\61\74\69\6f\6e\61\6c\70\65\72\73\6f\6e)(objectclass=\69\6e\65\74\6f\72\67\70\65\72\73\6f\6e)(uid=)) - Selected: (entryuuid,*) - Time Elapsed: 471.78
We see that uid is not given, and it is because we use user_login instead of username, so the final decision was to change LoginController.php:
protected function credentials(Request $request)
{
return [
'uid' => $request->user_login,
'password' => $request->password,
];
}
After doing that, logging in was successful.
I am working on a Laravel application, we are very close to being done and the client suddenly wants us to implement some of the users to not have usernames and passwords, they want them to login with First Name, Last Name, and lasr 4 of there social, to make this work we also have a unique ID that will be provided in a link (for the rare case when 2 people have the same info)
We could split into multiple users tables, however that would require a major rework of almost the entire application as users is tied into it pretty tight
we have gotten the method to work, the problem is it breaks login for other users (including admins) who still will use username and password.
The first thing we have tried, is to try unsucessfuly to convince the client NOT to go with this route, but they have been hard set on it. Obviously we have tried to make routes so that a different login controller is used but with no luck, its always defaulting to loginController.
Standard login controller
<?php
namespace App\Http\Controllers\Auth\Standard;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class StandardLoginController 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;
protected function authenticated(Request $request, $user)
{
if ($user->user_type == 'Patient'){
if ($user->current_facility_id != null){
return redirect()->route('patient.dashboard');
}
}
return redirect('/home');
}
/**
* Where to redirect users after login.
*
* #var string
*/
//protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Alternate login controller for new login method
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
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;
protected function authenticated(Request $request, $user)
{
if ($user->user_type == 'Patient'){
if ($user->current_facility_id != null){
return redirect()->route('patient.dashboard');
}
}
return redirect('/home');
}
protected function validateLogin(Request $request)
{
$request->validate([
'linkID' => 'required|string',
'firstname' => 'required',
'lastname' => 'required',
'password' => 'required|string',
]);
}/**/
public function username() {
return 'linkID';
}
protected function credentials(Request $request)
{
return $request->only($this->username(), 'password', 'firstname', 'lastname');
}
/**
* Where to redirect users after login.
*
* #var string
*/
//protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
routes from web.php
Route::view('standard-login', 'auth.standard.login');
Route::post('standard-login', 'Auth\Standard\StandardLoginController#login');
additionally some code from the users model
public function getAuthPassword()
{
if($this->user_type == 'Patient')
{
return $this->last4ssn;
}
return $this->password;
}
ideally we will have two login portals
1. will use first name, last name, and last 4 of the social, and a unique id as a url parameter that is hidden (if no parameter, it can be typed in)
2. we will have a standard login using username and password
Issue has been resolved, turns out i did not update action on the login form and it was referencing the wrong login controller as a result.
PROBLEM
I'm busy with my first Laravel app and although I see the benefits of the way things are written, I'm having a hard time understanding some of the behaviour.
When I try to login I get redirected to the login page. It seems like the user authenticates correctly, but it redirects to the login page regardless.
WHAT I HAVE
My users table looks like this:
,---------,---------------,---------------,----------------,---------------,-----------,
| user_id | user_username | user_password | user_firtsname | user_lastname | user_type |
|---------|---------------|---------------|----------------|---------------|-----------|
| 1 | me#domain.com | encrypted | Foo | Bar | farmer |
'---------'---------------'---------------'----------------'---------------'-----------'
This is my routes file:
<?php
Route::get('/login', 'UsersController#login');
Auth::routes();
Route::get('/dashboard', 'HomeController#dashboard')->name('dashboard');
Route::get('/users/grid', 'UsersController#grid');
Route::resource('/users', 'UsersController');
LoginController.php
<?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;
/**
* #var string
*/
protected $redirectTo = '/dashboard';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* #return string
*/
public function username()
{
return 'user_username';
}
/**
* #param Request $request
* #param $user
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function authenticated(Request $request, $user)
{
return $user->user_type === 'farmer' ? redirect('/dashboard') : redirect('/admin');
}
}
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* #var array
*/
protected $fillable = [
'user_username', 'user_firstname', 'user_lastname', 'user_password',
];
/**
* #var array
*/
protected $hidden = [
'user_password', 'remember_token',
];
/**
* #var bool
*/
public $timestamps = false;
/**
* #return mixed|string
*/
public function getAuthPassword()
{
return $this->user_password;
}
/**
* #return string
*/
public function getKey()
{
return $this->user_id;
}
}
WHAT I'VE DONE
I've read various questions on stackoverflow but for some reason I can't get login to work.
I created the auth using php artisan make:auth. I've tried reading the documentation too, but still no luck.
QUESTION
How do I get it to redirect to the dashboard after login? What am I missing?
You need to add this prop in your user model.
protected $primaryKey = 'user_id';
Remove the authenticated() method from login controller.
And handle the redirection based on user type inside RedirectIfAuthenticated middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if (Auth::guard($guard)->user->user_type === 'farmer'){
redirect('/dashboard'); // make sure the urls is correct with condition above
}
return redirect('/admin');
}
return $next($request);
}
}
Extra step inside App\Exceptions\Handler class
Add this method if you have different login pages for each user type
/**
* #param Request $request
* #param AuthenticationException $exception
* #return JsonResponse|RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
if ($request->is('dashboard') || $request->is('dashboard/*')) {
return redirect()->guest('/dashboard/login');
}
return redirect()->guest('farmer/login');
}
I have had the same problem yesterday night. I have found that the issue is Auth::attempt() does not persist the login so when a user is logged in successfully, it was dropped in the session after redirect to /home.
Below link provided the answer to solve it:
Laravel Auth:attempt() will not persist login
Try to add something like
protected $primaryKey = 'user_id'; in class User{}
(app/models/User.php)
(Field user_id is auto increment key in my Schema for 'users' table)
You are using user_password field instead of password field. So you need to do some changes in LoginController.php file. Below is the updated LoginController. Try to do changes like this and then try to login
<?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;
/**
* #var string
*/
protected $redirectTo = '/dashboard';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* #return string
*/
public function username()
{
return 'user_username';
}
/**
* #param Request $request
* #param $user
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function authenticated(Request $request, $user)
{
return $user->user_type === 'farmer' ? redirect('/dashboard') : redirect('/admin');
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'user_password' => 'required|string',
]);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
return $request->only($this->username(), 'user_password');
}
}
I added two functions validateLogin and credentials where default field was password. and I changed this with user_password.
for authentication in laravel first use php artisan make:auth command
and in your web.php add Auth::routes(); only which have all authentication routes
and to check if you are login or not you should add $this->middleware('auth'); in constructor of controller like
public function __construct()
{
$this->middleware('auth');
}
and do not forget to call auth class like use Auth;
or you can check authentication in your routes by add middleware auth
and also check https://laravel.com/docs/5.7/authentication documentaion
My focus is to show the user an error message called "You are inactive or not activated yet", if a user is tried to login with valid credentials but his status field is 0 ( Inactive ).
I am able to redirect a user to login page if his/her status is inactive by below function in LoginController.
protected function credentials(\Illuminate\Http\Request $request) {
return ['email' => $request->{$this->username()}, 'password' => $request->password, 'status' => 1];
}
How can I achieve this in laravel 5.4.
Any guide is helpful for me. Thanks in advance.
You can try to modify the sendFailedLoginResponse function in your LoginController.php
Path: app\Http\Controllers\LoginController
Remember to import Illuminate\Http\Request and App\User(Here is App\Models\User because I moved my User model to App\Models);
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Models\User;
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;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function credentials(Request $request) {
return array_merge($request->only($this->username(), 'password'), ['active' => 1]);
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
// Load user from database
$user = User::where($this->username(), $request->{$this->username()})->first();
// Check if user was successfully loaded, that the password matches
// and active is not 1. If so, override the default error message.
if ($user && \Hash::check($request->password, $user->password) && $user->active != 1) {
$errors = [$this->username() => trans('auth.notactivated')];
}
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
}
By the way, I add a line in resources\lang\en\auth.php so I can use trans('auth.notactivated') as my error message.
<?php
return [
'failed' => 'These credentials do not match our records.',
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
'notactivated' => 'This account has not been activated yet.',
];
i have a question, i want to redirect users to diferent pages after login based in the role, if is admin redirect to admin/users if is normal redirect to admin/norma for example i have the next files
LoginController.php
<?php
namespace App\Admin\Http\Controllers\Auth;
use App\Admin\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;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = 'admin/users';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required', 'password' => 'required', //'g-recaptcha-response' => 'required|recaptcha',
]);
}
}
And i use Laravel 5.3 and the Shinobi Package for roles and permissions https://github.com/caffeinated/shinobi
I already create 4 roles in the system database table roles - Administrador/Free/Gold/Diamond
I thinks is something how this
if($user->rol = 'Administrador){
protected $redirectTo = 'admin/users';
}else{
protected $redirectTo = 'admin/normal';
}
But i dont know how exactly make to work, thanks for all.
What you're looking for is the authenticated method override. Larvel calls this method after successful login to perform additional checks. You even get the user object and request object. You can perform the user role check and set the redirect path accordingly.
Add this to your LoginController
protected function authenticated(Request $request, $user)
{
if ($user->role == 'admin') {
$this->redirectTo = 'admin/dashboard';
} else {
$this->redirectTo = 'user/dashboard';
}
}
Edit : Since you're using the shinobi package. You need to do the role check like so
if ($user->isRole('admin')) {
}
I already solve my question in base to shinobi roles and the help of Sandeesh
I add this to my loginController.php
use Caffeinated\Shinobi\Models\Role;
use Caffeinated\Shinobi\Models\Permission;
and the function authenticated is now
protected function authenticated(Request $request, $user)
{
if( $user->isRole( 'administrador' ) ) {
$this->redirectTo = 'admin/dashboard';
} else {
$this->redirectTo = 'user/dashboard';
}
}
And now is working thanks for all :D