0

I have the typical scenario of an online newspaper where you have the article and below a form to comment, but where you need to login to comment. So on clicking it takes you to the log page and it should return you to that page once you have authenticated.

So, because the form is part of a page that the user can see without being logged in, I cannot write the middleware for that page created by a PostController, (get route).

The CommentController only has one method, which is the store one for the Form. so, of course, if I placed a middleware for that controller, it would fail because although it would indeed take you to the login page on clicking the submit button, the Intended URL saved would be that Post for the form, so on returning after authenticating, it would take you to a non existent URL page under the name of the Post route for that Form.

I have read about Auth::guards and the like but could not come clear with it,

This Laravel 5 - After login redirect back to previous page

asks exactly the same question that I do, it is the same scenario, but I dont see how his answer works, because defining a protected variable (and I have that already) like protected $redirectTo in the Auth controller only tells where to go after authenticating, and it is only a fixed route, in my case it takes you to the dashboard. But I dont want to be taken to the dashboard, it has to return to the page where the article and the comment form are.

Community
  • 1
  • 1
Arminius
  • 606
  • 1
  • 6
  • 19

2 Answers2

0

I found the solution at Laracasts. I must say I really dont understand it, but it works. It adds two functions to the AuthController.

https://laracasts.com/discuss/channels/laravel/redirect-to-page-where-login-button-was-clicked

public function showLoginForm()
        {
            if(!session()->has('from')){
                session()->put('from', url()->previous());
            }
            return view('auth.login');
        }

        public function authenticated($request,$user)
        {
            return redirect(session()->pull('from',$this->redirectTo));
        }
Arminius
  • 606
  • 1
  • 6
  • 19
-1

It's been a while since i've done this, but this should work normally. You could add a GET param in your link from the comment section to login page.

http://....com/login?intended=http://yourredirectlink.com/#form

Put the intended url in in the session variable url.intended and after login you redirect like so

Redirect::intended('/');

This will redirect back to the the url '/' if the session variable is not available.

Gregory
  • 1,148
  • 1
  • 9
  • 24