2

I have a web app where users can look at different postings and apply to the ones they want.

However when a user is not authenticated and he presses on the "Apply" Button, he then gets redirected to the Login window. After Logging in he SHOULD get redirected to the post he pressed the "Apply" Button.

Right now he just gets redirected, as normal, to the overview of posts.

I have no idea how to google stuff on it, since I don't know what this kind of redirection is called.

Any help appreciated

newbie
  • 525
  • 2
  • 12
  • 1
    Does this answer your question? [Laravel 5 - After login redirect back to previous page](https://stackoverflow.com/questions/29954791/laravel-5-after-login-redirect-back-to-previous-page) – CBroe Feb 02 '22 at 11:17
  • Mentioned duplicate is a bit older, so if this does not work any more in the described ways in a current Laravel version, then do a bit of research, what the correct replacements are. – CBroe Feb 02 '22 at 11:18
  • @CBroe thanks for the link! I actually found the exact same post, but it isn't the previous page I want to redirect to. It works like this: ```Post overview -> Post details with "Apply" Button -> (on press) new page with application form``` So without being authenticated something like this: ```Post overview -> Post details with "Apply" Button -> (on press)Login Window -> new page with application form``` – newbie Feb 02 '22 at 12:43
  • Then you would probably have to replace the `url()->previous()` part used in several of the solution shown there, with something that gives you the URL to that actual post you want to return to. But to get that URL, you will probably have to pass it along from the apply button already somehow, because I don't think Laravel tracks the path across _multiple_ different pages for you already. – CBroe Feb 02 '22 at 12:58
  • @CBroe sounds logical, thanks for the push in this direction, will dig deeper =) – newbie Feb 02 '22 at 16:51

1 Answers1

1

After trying around a little bit and failing a lot, I finally found a solution!

First I get the previous URL like this: $url = url()->previous()

then I get the part of the url after the / like this: $id = substr($url, strrpos($url, '/') + 1);

In the login controller I check what the url contains, if it contains the specific route the user has to come from to not get redirected to the standard after login page I do this:

if (str_contains($url, 'bewerben')) {
        return redirect()->to('/bewerben/' . $id);
 }

The bewerben route looks like this in my web.php file:

Route::get('/bewerben/{post}', [PostController::class, 'getDetails'])->name('details')->middleware('portal');

This is why I needed the $id

If the user comes from every other previous url I just redirect him to the standard after login page:

 else {
     return redirect()->intended(route('overview'));
}
newbie
  • 525
  • 2
  • 12