URL :: previous () returns incomplete path

8

As I'm studying the book Code Bright , I get errors from time to time. But this one did not find a solution in Google.

When doing Redirect::to() from one route to another should be displayed the previous full address, but only appears the URL of my vhost without the rest of the route.

Code of the book Code Bright:

Route::get('first', function()
{
    // redirect to the second route
    return Redirect::to('second');
});

Route::get('second', function()
{
    return URL::previous();
});

When I enter endereço/first and I'm redirected to the endereço/second route, it should be written endereço/first but only address appears.

Question

What would be the correct solution to resolve the impression of the return url?

Detail, I checked in github that I understand the Redirect::to generates a call 302 that does not transmit the information from where the route request is coming from. Maybe I'm wrong about this.

    
asked by anonymous 23.01.2014 / 20:59

1 answer

4

The URL::previous() method is based on HTTP Referer which is roughly an information that your browser sends to the site being accessed in the request header ( HTTP Headers ), informing you what URL the user was when you made the request. p>

This behavior of sending Referer is not homogeneous and your browser may not be sending this information.

To verify that the HTTP Referer header has been sent or not, you can do the following:

//  PHP "puro"
echo $_SERVER['REFERER'];

// Laravel
echo Request::header('referer');

If the user reloads the page, this information will be lost, it only exists if the user is accessing the page through a Link ( <a /> )

The best practice is to implement a mechanism that saves the current page in session, like this:

// Use como filtro, antes das rotas, ou em seu controller, 
// o importante é executar o código em todas as páginas
if(Session::get('url_atual')) {
    Session::put('url_anterior', Session::get('url_atual'));
} 
Session::put('url_atual', URL::current());

And then, if you need to create or link or make a redirect leading to the previous page, just use:

Redirect::to(Session::get('url_anterior'));
  

Note1: The example above is ported, use it cautiously on a production system.


  

Note 2: See Method Implementation in:    link   lines 72 to 82:

public function previous()
{
    return $this->to($this->request->headers->get('referer'));
}
    
24.01.2014 / 14:42