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

miwal's avatar
Level 11

redirect back withoutQueryParameters ?

I'm looking for a function which would do this:

redirect()->back()->withoutQueryParameters()

Specifically the back location may contain a query string ( e.g. ?something=somethingelse) appended to the url. I want to redirect back there with that bit removed, just to the base url.

I scanned the source for back() and couldn't see how.

0 likes
9 replies
cometads's avatar
cometads
Best Answer
Level 3

You can access the previous url with url()->previous().

So, get that, strip the query params and redirect to it.

return redirect()->to(preg_replace('/\?.*/', '', url()->previous()));

1 like
miwal's avatar
Level 11

Super neat - that works, thanks.

However... I now realise my quest for this method was largely to get readable code... !

I know where I'm redirecting back to in this instance, and didn't want to redirect to the actual route name because that makes the intention in the controller less clear. "back without query params" states exactly what the code intends to do.

The regex is lovely but again maybe it's not very scannable/readable?... or maybe it is, its a nice tool of course.

I guess it's not possible to somehow be able to write ->withoutQueryParameters() since we probably can't or don't want to override the request class; or is anything like that possible neatly within laravel?

jlrdw's avatar

Make a withoutQueryParameters method in a helper, It's a PHP framework you are free to custom code as needed.

Snapey's avatar

make it in your controller..

    return $this->redirectBackWithoutQuery();
}


private function redirectBackWithoutQuery()
{

    return redirect()->to(preg_replace('/\?.*/', '', url()->previous()));

}

or


private function redirectBackWithoutQuery()
{
    return explode('?',url()->previous())[0];
}

1 like
jlrdw's avatar

But putting in a helper would make it reusable anywhere. Unless of course you only needed in that one controller only.

And I think it would have been a wonderful learning experience to code that yourself, but that's just my opinion.

cometads's avatar

I don't think my answer is super unreadable, especially if you have a strong grasp of Laravel's helpers and regex.

Regardless we're discussing abstraction at this point which has countless implementations and is largely personal preference. I'd agree with both replies. If you intend to repeat this code, use a global helper. If it's scoped to this Controller/Model make a private function.

Or, maybe, make a Trait. Do you. Whatever feels comfortable. Either way that regex (or explode) and helper is still the best option and will still exist in your code base.

miwal's avatar
Level 11

I actually realised the helper function was an option before I read these replies. The way I prefer to add helpers is to use a class, import it and use statics, like MyApp::redirectBackWithoutQuery(). I saw @themsaid use that in his wonderful writingink/wink source code. He writes the framework so I figure copying his style is not a terrible idea.

To me it it's not too attractive to put these kind of things in individual controllers at this point, the moment you use it in more than one you've got code duplication (I am seeking to improve my style and get better at writing more maintainable code). So I've put it on the base controller class so can call $this->redirectBackWithoutQuery(). Not bad.

But may I ask the experts here out of curiosity (and in order to improve understanding of the abstraction options which are available) -- is it possible in any way to actually set things up so we can do return request()->back()->withoutQuery() ?

Can one override the Request class, if that's the right thing do achieve that, within Laravel and bind the new inherited class into the container instead? I have not mucked about with rebinding much yet.

A few tips/hints would be cool -- I'm happy to also go and research this myself too.

Thanks to all, especially to @cometads who solved this first and fast.

Update: reflecting on it further, I suppose there's a good argument that since you can easily add a global helper (so long as we're ok with that), then since that would let you do just return backWithoutQuery(), then one could argue what's the point of overriding the Request class even if it's possible... would be a fair point.

Update 2: I've gone with the global helper for now. One niggling doubt was/is, if global helpers in user land of the framework are a good idea, why does the framework not set that up for you? Maybe the answer is, I'm speculating here, is that if they are added they might be abused a bit or confuse beginners, and they are not hard to add if needed when someone with more experience knows they want them. I wonder what the general expert consensus on that is here, if that's approximately it. (as to why the decision appears to have been taken not to set up a file 'helpers.php' by default in the application skeleton laravel/laravel).

Update 3: I've changed my mind. The reason: putting this method on the controller base class seems a sufficient level of abstraction. I never (though one never knows the future) need this method outside of a controller. When I see a global, right now I know it's a framework global, so starting to add my own (viz., just for this) pays the price of changing that simple understanding. Yes with today's code editors you can just click through to see a function definition, but that just alleviates the cognition problem, that fact doesn't actually generate simplicity in itself.

miwal's avatar
Level 11

The real answer to this which I was introduced to by reading Matt Stauffer's new edition seems to be what Taylor has christened "macros" in laravel (with sincere apologies to anyone who knows Lisp/Clojure - these have no relation whatsoever to the real concept of macros there, unchanged since the 1960s and one of the most wonderful things in all of computer science). In these laravel thingys, or I can say add-a-functions, you can add a new function onto an existing class, including the request, so this appears to achieve (by a shortcut) exactly what I was looking for here.

Amusingly, I have just done a search online to find out if there is an existing name for "adding a function to an existing class" . It turns out what this should have been called is Request::monkeyPatch('name-of-new-function', function() {... }) :) I guess that's why Taylor chose a more mysterious sounding name instead.

To see the other perspective, since this is within the context of a framework, this monkey patching isn't as bad as "real monkey patching", perhaps (indeed, it's potentially helpful here - remains to be seen) but I think it still would be more accurate and helpful to call it what it is, since this name already exists for this action. As it stood, I had read about these things in laravel before, but always had a kind of 'what is that' reaction, perhaps because of the strange name. Hopefully this time I'll remember if I actually need it again (only for exceptional cases, of course).

Even just Request::addFunction('name-of', function() { ... }) could have done the job re. naming there! Does anyone else use these?

miwal's avatar
Level 11

So, in boot of a service provider, e.g. MonkeyPatchServiceProvider, I have this:

RedirectResponse::macro('withoutQuery', function() {
    return redirect()->to(explode('?', url()->previous())[0]);
});

which means my controller code now reads:

return back()->withoutQuery();

Works fine & dandy, but it'll take time to see if I like this or not. May prefer it in base controller class, and use monkey patches only for emergencies.

Please or to participate in this conversation.