D
D
Dmitry2019-07-06 14:36:55
Laravel
Dmitry, 2019-07-06 14:36:55

Laravel 5.2 redirect to previous page while keeping get parameters?

The bottom line: on the main page there is a catalog of images and filters for them (by type, author, color, etc.), which are transmitted by the GET method. Registered user can add them to cart. If the user is not authorized, by clicking on the "add to cart" button, he will be redirected to the authorization page, and after entering the login / password, he returns to the main page. The question is how to return it to the main page while preserving the get-parameters, i.e. not on site.com but on site.com/?perPage=36&page=3&color=red

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Sokharev, 2019-07-06
@sintez007

For example, Laravel has an intended mechanism. You can see how it works and do something similar.
Of course, we are most interested in the methods guestand intendedclasses of Illuminate\Routing\Redirector .

/**
     * Create a new redirect response, while putting the current URL in the session.
     *
     * @param  string  $path
     * @param  int     $status
     * @param  array   $headers
     * @param  bool    $secure
     * @return \Illuminate\Http\RedirectResponse
     */
    public function guest($path, $status = 302, $headers = [], $secure = null)
    {
        $this->session->put('url.intended', $this->generator->full());

        return $this->to($path, $status, $headers, $secure);
    }

   /**
     * Create a new redirect response to the previously intended location.
     *
     * @param  string  $default
     * @param  int     $status
     * @param  array   $headers
     * @param  bool    $secure
     * @return \Illuminate\Http\RedirectResponse
     */
    public function intended($default = '/', $status = 302, $headers = [], $secure = null)
    {
        $path = $this->session->pull('url.intended', $default);

        return $this->to($path, $status, $headers, $secure);
    }

As we can see, there is no black magic going on here. It's just that when redirecting to the authentication page, the url is added to the session. And after the user has successfully passed authentication, a redirect is made back to the url saved earlier in the session.
Implement a similar mechanism with your own nuances and you will be happy.
In general (if your task is fully described in your question) it will be enough to do this:
if(auth()->guest()) {
    session()->put('url.intended', url()->full());

    return redirect()->route('auth');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question