Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Custom login redirects to /home instead of a /welcome page

Tags:

php

laravel

I am trying to create a custom login. After login, it lands to '/home' page instead of '/welcome' page.

Here is my Login Controller :

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/welcome';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function view()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $this->validate($request, [
                'email'    => 'required',
                'password' => 'required',
            ]);

        $loginValue = $request->input('email');

        $login_type = $this->getLoginType($loginValue);

        $request->merge([
            $login_type => $loginValue
        ]);

        if (auth()->attempt($request->only($login_type, 'password'))) {
            // return redirect()->intended($this->redirectPath());
            return redirect()->intended(route('welcome'));
        }
        return redirect()->back()->withInput()->withErrors([ 'email' => "These credentials do not match our records." ]);
    }

    public function getLoginType($loginValue)
    {
        return filter_var($loginValue, FILTER_VALIDATE_EMAIL ) ? 'email'
       : ( (preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \/]?)?((?:\(?\d{1,}\)?[\-\.\ \/]?){0,})(?:[\-\.\ \/]?(?:#|ext\.?|extension|x)[\-\.\ \/]?(\d+))?$%i', $loginValue)) ? 'mobile' : 'name' );
    }
}

I have change the redirect path from Illuminate\Foundation\Exception\Handler.php :

protected function unauthenticated($request, AuthenticationException $exception)
{
  return $request->expectsJson() ? response()->json(['message' => $exception->getMessage()], 401 : redirect('/');
}

My routes file:

Route::get('/login', 'Auth\LoginController@view')->name('login');
Route::post('/login', 'Auth\LoginController@login');
like image 535
tanjiya Avatar asked Dec 15 '25 05:12

tanjiya


2 Answers

If you would like to redirect to "/Welcome" page. You should require changes in a middleware.

Middleware: RedirectIfAuthenticated.php

Following changes needed.

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect('/welcome');
    }
    return $next($request);
}

change return redirect to "/welcome" instead of "/home".

I hope this solution can be help to solve your problem. Thanks.

like image 65
Amit Senjaliya Avatar answered Dec 16 '25 22:12

Amit Senjaliya


In Larave 8.0,

Modify the public const HOME as '/' instead of '/Home' in app/Providers/RouteServiceProvider.php

like image 24
Sibi E Avatar answered Dec 16 '25 20:12

Sibi E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!