Laravel 5.1 add Query strings in url
17,717
Solution 1
Query strings shouldn't be defined in your route as the query string isn't part of the URI.
To access the query string you should use the request object. $request->query()
will return an array of all query parameters. You may also use it as such to return a single query param $request->query('key')
class MyController extends Controller
{
public function getAction(\Illuminate\Http\Request $request)
{
dd($request->query());
}
}
You route would then be as such
Route::get('/category/{id}');
Edit for comments:
To generate a URL you may still use the URL generator within Laravel, just supply an array of the query params you wish to be generated with the URL.
url('route', ['query' => 'recent', 'order' => 'desc']);
Solution 2
if you have other parameters in url you can use;
request()->fullUrlWithQuery(["sort"=>"desc"])
Author by
Arnab Rahman
Updated on July 28, 2022Comments
-
Arnab Rahman over 1 year
I've declared this route:
Route::get('category/{id}{query}{sortOrder}',['as'=>'sorting','uses'=>'CategoryController@searchByField'])->where(['id'=>'[0-9]+','query'=>'price|recent','sortOrder'=>'asc|desc']);
I want to get this in url: http://category/1?field=recent&order=desc How to achieve this?
-
Arnab Rahman over 8 yearsYou misunderstood my question. I get it what you're saying. But i want to do that with query strings.
-
Arnab Rahman over 8 yearsOk. So, how do i call this from my view?
-
Wader over 8 yearsYour options are to set variables in your controller and pass them into your view as normal (I would advise this as you can then validate them. Remember they're user input!). Or you can use the facade directly in your view
Request::query()
-
Arnab Rahman over 8 yearsThe thing is that i was doing
<a href={{url('route_url'}}></a>
this. I guess now i can't do that. -
Wader over 8 yearsYou should still be able to do that, I've updated my answer with an example for generating URLs with query strings
-
Arnab Rahman over 8 yearsHmm almost figured this out. Now, only problem is that i already have a route declared
category/{id}','CategoryController@index'
and{!! link_to_action('CategoryController@customQuery',null,['id'=>1,'query'=>'price','order'=>'desc]) !!}
goes to index method rather than going to customQuery method -
Peter Chaula about 7 yearsThe last part doesn't work in Laravel 5.3.Output is
http://localhost/route/recent/desc
-
Amir Hassan Azimi over 6 yearsGOLD answer! Thanks