Laravel - login redirection loses URL hash

When I want to share the URL of a page from my site, for example mysite.com/page1#foo=bar , or I want to visit this page when I log out, I am redirected to the login form because the route of page1 is in auth middleware .

My problem is that after a successful login, I get redirected to mysite.com/page1 and I lose the hash value.

(the hash value is also not saved on /login )

Is there an easy way provided by Laravel to store the hash? Since the hash is not sent to the server, I kind of doubt it, but maybe I missed something!

Otherwise, I will need to rewrite the login, perhaps read the hash with JS and somehow re-enter it in the redirection after logging in, but I would like to avoid this if there is an easy way :)

+6
source share
2 answers

Thanks to the direction of Mruf, I was able to figure this out. Not sure if this is the best implementation, but it seems to work.

Basically, I paste the hash value into the form, as Mruf suggested, and then extend the handleUserWasAuthenticated function in AuthController

login.blade.php

 <script type="text/javascript" > $( document ).ready(function() { $('.urlHash').val(window.location.hash); }); </script> <form id="login-form" role="form" method="POST" action="{{ url('/login') }}"> <input type="hidden" class="form-control urlHash" name="urlHash" value=""> .... </form> 

AuthController.php

 protected function handleUserWasAuthenticated(Request $request, $throttles) { if ($throttles) { $this->clearLoginAttempts($request); } if (method_exists($this, 'authenticated')) { return $this->authenticated($request, Auth::guard($this->getGuard())->user()); } // old code: return redirect()->intended($this->redirectPath()); $newRequest = redirect()->intended($this->redirectPath()); $newRequest->setTargetUrl($newRequest->getTargetUrl() . $request->urlHash); return $newRequest; } 
+1
source

Simple JavaScript will do the trick:

 $("#login-form").submit(function(){ e.preventDefault(); $(this).append("<input type='hidden' name='hash' value='"+window.location.hash+"'"); $(this).submit(); }); 

Now you can access the hash in the request object

 function controllerAction(Request $request){ $hash = $request->get("hash"); // Parse Hash .... // Redirect to somewhere .... } 
+2
source

Source: https://habr.com/ru/post/1012410/


All Articles