Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rotaercz's avatar

Question about getting the current url of the page the user is on

So in my controller I'd like to get the current page url the user is on.

I use Ajax on the client side, something like this:

$.ajax({
    type: 'POST',
    url: {{ url('/loadcomments') }},
    // etc.
});

When I get the current url in my controller I'll get {{ url('/loadcomments') }} which is not what I want but I noticed if I use:

url()->previous()

This provides the correct URL. Which makes sense since the last url was {{ url('/loadcomments') }}.

My question is, is it ok to do it this way? Or are there edge cases where this would provide unexpected results?

Originally I passed the current URL as data via Ajax but I was trying to make it a bit more elegant. Are there any edge cases I should take in to consideration or is it fine to do it this way?

0 likes
6 replies
jlrdw's avatar

If using ajax, you can just pre-build a variable of page (uri) needed. But ajax doesn't always match the current uri as things are happening in the background.

Snapey's avatar

send it from the client with the request. I think what you are doing now is just getting the url where you sent the ajax to.

rotaercz's avatar

So you recommend:

$.ajax({
    type: 'POST',
    url: {{ url('/loadcomments') }},
    data: {
        current_url: {{ Request::path() }}
    }
});

and just referencing current_url in the request in the controller?

I was actually doing it this way originally but was hoping to remove the data part entirely so it would be cleaner.

Cronix's avatar

In your ajax url you don't need to use blade, you could just use

url: '/loadcomments',

You also don't need to use blade to get the current url, you can get that from the javascript window.location.

current_url: window.location

This is better anyway, because then your code can just live in a standalone js file and doesn't need to be parsed by php/blade, which is better than having js littered throughout your page and keeps things separated.

1 like
rotaercz's avatar

Appreciate the reply.

Is using

url()->previous()

in the controller not optimal? I'm trying to simplify the ajax by removing the data part entirely. Just scratching my head here regarding this part.

rotaercz's avatar
rotaercz
OP
Best Answer
Level 3

It seems what I'm looking for is:

Request::server('HTTP_REFERER')

Thank you to everyone that replied.

Please or to participate in this conversation.