Julian Mendez
Julian Mendez

Reputation: 3372

Laravel redirect after anything

using laravel 5.6 right now, will update to 5.8 soon.

The question is simple, I want to redirect after login (for this time, just want to add some redirect logic in order to use it may be later). In this case, I set up the login middleware to send the $request->getBackURI() as a param to the login view.

Once I am on the login form I can see the redirect_to as a querystring, but when I do the login and I want to see the $request->get('redirect_to') it's empty, of course, because I didn't send it as a param to the actually login controller.

I saved it in the session of the request but suddenly an other variable I didn't see appeared

{session:
...
url => www.foo.bar/pathtoredirect,
redirect_to => /pathtoredirect} -> this is the one I stored

the thing is, once I get to the redirect method I really cant access to anything, it'a a void function

protected function redirectTo()
{
    return route('main.index');
}

if I include the Request object I get

Too few arguments to function App\Http\Controllers\Auth\LoginController::redirectTo(), 0 passed ... on line 15 and exactly 1 expected

I know, for this case that is just one redirect, from path -> login -> path I can use

protected function redirectTo()
{
    return back();
}

I just want to know if there is any way I can implement my way of doing the things or will the Laravel way works every single time I want (Ex: more than just 1 redirect, imagine some middlewares requests or facebook login)

Upvotes: 0

Views: 327

Answers (1)

Hamelraj
Hamelraj

Reputation: 4826

Hi you can overwrite default login function and after login function also in Laravel

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{

    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');
    }

    /**
    * The user has been authenticated.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  mixed  $user
    * @return mixed
    */
    protected function authenticated(Request $request, $user)
    {
      // in here you can do what ever you want 
        $path = $request->get('redirect_to')
        return redirect($path);
    }
} 

and globally you can call request without passing

protected function redirectTo()
{
   $path = request()->redirect_to;
   or 
   $path = \Request::get('redirect_to');
    return back();
}

Upvotes: 1

Related Questions