Laravel 5 - After login redirect back to previous page

前端 未结 13 2333
广开言路
广开言路 2020-11-30 04:41

I have a page with a some content on it and a comments section. Comments can only be left by users who are signed in so I have added a login form to the page for users to si

相关标签:
13条回答
  • 2020-11-30 05:12

    Use Thss

    return Redirect::back('back-url')

    0 讨论(0)
  • 2020-11-30 05:17

    For Laravel 5.4, following code worked for me by just updating LoginController.php

    use Illuminate\Support\Facades\Session;
    use Illuminate\Support\Facades\URL;
    
    
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
        Session::put('backUrl', URL::previous());
    }
    
    
    public function redirectTo()
    {
        return Session::get('backUrl') ? Session::get('backUrl') :   $this->redirectTo;
    }
    
    0 讨论(0)
  • 2020-11-30 05:21

    Look into laravel cheat sheet

    and use:

    URL::previous();
    

    to go to the previous page.

    0 讨论(0)
  • 2020-11-30 05:21

    If you want to redirect always to /home except for those pages with comments, then you should overwrite your redirectTo method in your LoginController:

    public function redirectTo()
    {
         return session('url.intended') ?? $this->redirectTo;
    }
    

    On all pages where you want to remain on the site, you should store the url for one request in the session:

    public function show(Category $category, Project $project){
       // ...
    
       session()->flash('url.intended' , '/' . request()->path());
    }
    
    0 讨论(0)
  • 2020-11-30 05:22

    For Laravel 5.3

    inside App/Http/Controllers/Auth/LoginController add this line to the __construct() function

    $this->redirectTo = url()->previous();
    

    So the full code will be

    public function __construct()
    {
        $this->redirectTo = url()->previous();
        $this->middleware('guest', ['except' => 'logout']);
    }
    

    It works like a charm for me i'm using laravel 5.3.30

    0 讨论(0)
  • 2020-11-30 05:22

    Redirect to login with the current's page url as a query string:

    <a href="{{ url('login?redirect_to=' . urlencode(request()->url())) }}">login</a>
    

    In your LoginController check if exists and save the query string in session then redirect to the url after login

    public function __construct() {
            parent::__construct();
            if ( \request()->get( 'redirect_to' ) ) {
                session()->put( 'redirect.url', \request()->get( 'redirect_to' ) );
            }
            $this->middleware( 'guest' )->except( 'logout' );
    }
    
    protected function authenticated(Request $request, $user) {
            if(session()->has('redirect.url') {
                 return redirect( session()->get( 'redirect.url' ) );
            }
    }
    
    0 讨论(0)
提交回复
热议问题