maximus1127
maximus1127

Reputation: 1036

Redirect two pages back with url()->previous() in laravel

I'm creating an affiliate tracking system with some custom affiliate links. These links trigger a controller function to store some metrics in the database then redirect to the actual page the user intended.

My desired function is this: insert affiliate link into webpage->user clicks->controller fires/data stored->redirect to intended page. One of the pieces of data I want to store is the originating site the user clicked on the link. But because I'm calling the controller with a URL, url()->previous() gets my affiliate link that fired the controller instead of the originating site that has the link embedded.

I'm not sure if "previous()" can accept parameters but i tried "previous(2)" and that obviously didn't work.

$url = url()->previous();
$click->came_from = $url;

Using the code above, if my link was hosted on www.w3schools.com and my affiliate link is myurl/affiliatelink/2, I would want "www.w3schools.com" to be inserted into my database, but i'm getting "myurl/affiliatelink/2" inserted instead. Can anyone help me figure out a way around this?

Upvotes: 0

Views: 4003

Answers (2)

ovo
ovo

Reputation: 71

You can simply get and store the previous url with the parameter in a variable($url) from your blade file, then pass the variable to your anchor tag as shown below:

@php 

   $url= url()->previous(); 

@endphp

href="{{url($url)}}"

This works very fine.

Upvotes: 0

Augusto Moura
Augusto Moura

Reputation: 1392

The previous() method returns the user's last location within the app, not the last URL the browser accessed.

To do that, in Laravel, you can try Request::server('HTTP_REFERER'), or in plain PHP, $_SERVER['HTTP_REFERER'].

That said, be aware that HTTP_REFERER is not exactly the most reliable value. It can be spoofed (faked) easily or not provided at all, so test accordingly.

If possible, the best option would be to add a GET parameter to the link present in the remote site, so that when you receive the request in your Controller, you have the means to identify where the user is coming from.

Upvotes: 2

Related Questions