How to redirect after login with condition in laravel 5.4,
As Like:
if (Auth::user()->id==1) {
return redirect('admin');
}
else {
return redirect('/');
}
How to implement the condition.
Add following code in LoginController
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;
/**
* Where to redirect users after login.
*
* #var string
*/
//protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
protected function authenticated(Request $request, $user)
{
if ( $user->isAdmin() ) {// do your magic here
return redirect()->route('dashboard');
}
return redirect('/home');
}
}
#Al-Amin to redirect after login successfully based on role id you can override authenticated(Request $request, $user) function in your Auth Controller or Login Controller if you have in below manner :
/**
* [authenticated is used to redirect user after login based on role]
* #param Request $request [request object]
* #param [type] $user [user object to check user role]
* #return [type] [return type]
*/
protected function authenticated(Request $request, $user)
{
if($user->role->id == 1) {
return redirect()->intended('/admin'); // it will be according to your routes.
} else {
return redirect()->intended('/'); // it also be according to your need and routes
}
}
This is the method which you should change in RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/dashboard'); // Change this line
}
return $next($request);
}
Related
I am using a custom guard for a different type of user using a custom guard labelled business_user.
I have noticed I am able to login to as both normal users (web) and my business_users.
I've read in the Pusher documentation that I used to create my custom guards in the first place to add additional middleware into my "LoginController".
But I don't actually even have a LoginController, I've created my own controllers for each user type. AuthController (for web) and BusinessController (for business_user).
I have created a third controller labelled LoginController with the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/dashboard';
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:business_user')->except('logout');
}
}
I also updated my RedirectIfAuthenticated as follows:
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if ($guard == "business_user" && Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
I also have a RedirectIfAuthenticated middleware inside my Middleware folder.
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
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 ($guard == "business_user" && Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
}
When I land on my user login page, it still allows me to attempt logging in. Can someone tell me how to resolve this?
In LoginController, you can override authenticated method.
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
auth()->login($user); // this method will login with default guard
return redirect()->intended($this->redirectPath());
}
I think because the order of middleware
<?php
public function __construct()
{
$this->middleware('guest')->except('logout'); // this procress first and redirect to login page
$this->middleware('guest:business_user')->except('logout');
}
So, I think you can check directly in __construct() of LoginController or in login view (blade file)
#if (Auth::check('business_user'))
You are already logged in (or perform a redirect somewhere)
#else
//display login form
#endif
I am using Laravel project version 5.8.
I have used two middleware Admin and Author.
I have created both AdminMiddleware and AuthorMiddlware.
I registered both in Kernel.php. I changed RedirectIfAuthenticated, loginController for custom redirect. I have created different route groups.
For admin middleware it will redirect admin.dashboard and for author middleware it will redirect to author.dashboard.
After then, it is redirecting to the /home route as in the default laravel logged in users. I want to redirect admin to admin.dashboard and author to author.dashboard after login.Custom redirect is not working. I viewed my project several times but unable to find the issue.
loginController.php
// protected $redirectTo = '/home';
public function __construct(){
if(Auth::check() && Auth::user()->role->id==1) {
return redirect()->route('author.dashboard');
} else if (Auth::check() && Auth::user()->role->id==2) {
return redirect()->route('admin.dashboard');
}else {
$this->middleware('guest')->except('logout');
}
}
RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null){
if (Auth::guard($guard)->check() && Auth::user()->role->id==1) {
return redirect()->route('author.dashboard');
}else if (Auth::guard($guard)->check() && Auth::user()->role->id==2) {
return redirect()->route('admin.dashboard');;
} else {
return $next($request);
}
}
AuthorMiddleware
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->role->id==1){
return $next($request);
} else {
return redirect()->route('/login');
}
}
AdminMiddleware
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->role->id==2){
return $next($request);
} else {
return redirect()->route('/login');
}
}
Web.php
Route::group(['as'=>'author.','prefix'=>'author','namespace'=>'Author','middleware' => 'author'], function () {
Route::get('/dashboard','DashboardController#index')->name('dashboard');
});
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware' => 'admin'], function () {
Route::get('/dashboard','DashboardController#index')->name('dashboard');
});
Author/DashobardController
public function index()
{
return view('author.dashboard');
}
Admin/DashobardController
public function index()
{
return view('admin.dashboard');
}
I am new in Laravel. Faced this problem first time and unable to find issues please help.
You need to edit the following lines into your LoginController.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;
protected function authenticated(Request $request, $user)
{
if(Auth::check() && Auth::user()->role->id==1) {
return redirect()->route('author.dashboard');
} else if (Auth::check() && Auth::user()->role->id==2) {
return redirect()->route('admin.dashboard');
}
return redirect('/home');
}
/**
* Where to redirect users after login.
*
* #var string
*/
//protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
}
Change
RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null){
if (Auth::guard($guard)->check() && Auth::user()->role->id==1) {
return '/author/dashboard';
}else if (Auth::guard($guard)->check() && Auth::user()->role->id==2) {
return 'admin/dashboard';
} else {
return $next($request);
}
}
Or
public function handle($request, Closure $next, $guard = null){
if (Auth::user()->role->id==1) {
return '/author/dashboard';
}else if (Auth::user()->role->id==2) {
return 'admin/dashboard';
} else {
return $next($request);
}
}
Logincontoller.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;
protected function authenticated(Request $request, $user)
{
if(Auth::check() && Auth::user()->role->id==1) {
return 'author/dashboard';
} else if (Auth::check() && Auth::user()->role->id==2) {
return 'admin/dashboard';
}
return redirect('/home');
}
/**
* Where to redirect users after login.
*
* #var string
*/
//protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
}
I have some roles asigned to users. I would like to have a user redirected after login to different urls in order the role that user belongs to.
I have followed this post but it didn't work to me. I don't know if using backpack it would be different.
Best regards.
Edit.
This is the code in the login controller.
<?php
namespace Backpack\Base\app\Http\Controllers\Auth;
use Backpack\Base\app\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller{
protected $data = []; // the information we send to the view
protected $redirectTo = '/home';
/*
|--------------------------------------------------------------------------
| 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 {
logout as defaultLogout;
}
protected function authenticated(Request $request, $user){
/*if ( $user->isAdmin() ) {// do your margic here
return redirect('/home1');
}*/
return redirect('/myhome');
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$guard = backpack_guard_name();
$this->middleware("guest:$guard", ['except' => 'logout']);
// ----------------------------------
// Use the admin prefix in all routes
// ----------------------------------
// If not logged in redirect here.
$this->loginPath = property_exists($this, 'loginPath') ? $this->loginPath
: backpack_url('login');
// Redirect here after successful login.
$this->redirectTo = property_exists($this, 'redirectTo') ? $this->redirectTo
: backpack_url('dashboard');
// Redirect here after logout.
$this->redirectAfterLogout = property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout
: backpack_url();
}
/**
* Return custom username for authentication.
*
* #return string
*/
public function username()
{
return backpack_authentication_column();
}
/**
* Log the user out and redirect him to specific location.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
// Do the default logout procedure
$this->guard()->logout();
// And redirect to custom location
return redirect($this->redirectAfterLogout);
}
/**
* Get the guard to be used during logout.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return backpack_auth();
}
// -------------------------------------------------------
// Laravel overwrites for loading backpack views
// -------------------------------------------------------
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
$this->data['title'] = trans('backpack::base.login'); // set the page title
$this->data['username'] = $this->username();
return view('backpack::auth.login', $this->data);
}
}
If I put this code in the path
vendor\backpack\base\src\app\Http\Controllers\Auth\LoginController.php
It works fine. But If I put the code in
app\Http\Controllers\Auth\LoginController.php
It does not work
I'm trying to extend the controller like this
use Backpack\Base\app\Http\Controllers\Auth\LoginController as OriginalLoginController;
class MyLoginController extends OriginalLoginController{
.....
}
To create a redirect in Laravel:
<?php
if($x){
return redirect()->route('routeName1', [$arr, $of, $params]);
}
else if($y){
return redirect()->route('routeName2', [$arr, $of, $params]);
}
My 'users' table has a 'role' column and when users are registered or logged in, I want them to be redirected based on their role column. how can I do that?
I added this function to AuthController.php and everything fixed magically
public function authenticated($request , $user){
if($user->role=='super_admin'){
return redirect()->route('admin.dashboard') ;
}elseif($user->role=='brand_manager'){
return redirect()->route('brands.dashboard') ;
}
}
If you are using the Authentication system provided with Laravel you can override the redirectPath method in your Auth\AuthController.
For example, this would redirect a user with role 'admin' to /admin and any other user to /account:
public function redirectPath()
{
if (\Auth::user()->role == 'admin') {
return "/admin";
// or return route('routename');
}
return "/account";
// or return route('routename');
}
You could also use Laravel Authorization (introduced in 5.1.11) to manage role logic.
In laravel 5.7 there is no AuthController.php so you have to go Controllers\Auth\LoginController.php and add the below function,
If the redirect path needs custom generation logic you may define a redirectTo method instead of a redirectTo property
protected function redirectTo()
{
if($user->role=='super_admin'){
return '/path1';
}elseif($user->role=='brand_manager'){
return '/path2';
}
}
You can do this handle the request in the Middleware RedirectIfAuthenticated.php inside the handle function like this:
/**
* 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::user()->role == 'admin') {
return redirect('/admin');
}else{
return redirect('/');
}
}
return $next($request);
}
I write this in case someone consider useful. If you want to redirect always and not only on Login, I did it on web.php like this:
Route::get('/home', function () {
switch(\Illuminate\Support\Facades\Auth::user()->role){
case 'admin':
return redirect(route('home.admin'));
break;
case 'employee':
return redirect(route('home.employee'));
break;
default:
return '/login';
break;
}
});
Route::get('/home/admin', 'HomeController#indexAdmin')->name('home.admin');
Route::get('/home/employee', 'HomeController#indexEmployee')->name('home.employee');
So every time they click on /home is redirect to the url you want, you could do it too with '/'.
for laravel 9 i implement the following code
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Traits\HasRoles;
class LoginController extends Controller
{
use AuthenticatesUsers, HasRoles;
public function redirectTo(){
if(Auth::user()->hasAnyRole('Adm1','Adm2')){
return $this->redirectTo = route('viewAdm') ;
}elseif(Auth::user()->hasAnyRole('Usuario')){
return $this->redirectTo = route('home') ;
}
}
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
<?php namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterRequest;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use App\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
class AuthController extends Controller {
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers;
/**
* For redirect after registeration
* #return mixed
*/
public function redirectPath()
{
// return property_exists($this, 'redirectTo') ? $this->redirectTo : '/user/profile/';
//return property_exists($this, 'redirectTo') ? $this->redirectTo : '/';
return Redirect::intended('/');
}
/**
* Create a new authentication controller instance.
*
* #param \Illuminate\Contracts\Auth\Guard $auth
* #param \Illuminate\Contracts\Auth\Registrar $registrar
* #return \App\Http\Controllers\Auth\AuthController
*/
public function __construct(Guard $auth, Registrar $registrar)
{
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Handle a login request to the application.
*
* #param LoginRequest $request
* #return Response
*/
public function postLogin(LoginRequest $request)
{
if ($this->auth->attempt($request->only('email', 'password')))
{
if(Auth::user()->is_admin)
return redirect('/admin');
else {
return Redirect::intended('/');
}
}
return redirect('auth/login')->withErrors([
'email' => 'The credentials you entered did not match our records. Try again?',
]);
}
}
I am redirecting a user to an intended url after signup but i get the following error.
Header may not contain more than a single header, new line detected
This is the code in the AuthController.
public function redirectPath()
{
return Redirect::intended('/');
}
And the following is the code in the Authenticate class.
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('auth/register');
}
}
return $next($request);
}
I am using laravel 5