8

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
  • 1,003
  • 1
  • 9
  • 15

3 Answers3

18

if you have other parameters in url you can use;

request()->fullUrlWithQuery(["sort"=>"desc"])
Oğuz Can Sertel
  • 749
  • 2
  • 11
  • 26
3

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']);
Wader
  • 9,427
  • 1
  • 34
  • 38
  • Ok. So, how do i call this from my view? – Arnab Rahman Nov 16 '15 at 14:57
  • Your 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()` – Wader Nov 16 '15 at 14:59
  • The thing is that i was doing `` this. I guess now i can't do that. – Arnab Rahman Nov 16 '15 at 15:22
  • You should still be able to do that, I've updated my answer with an example for generating URLs with query strings – Wader Nov 16 '15 at 15:30
  • 1
    Hmm 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 – Arnab Rahman Nov 16 '15 at 16:23
  • The last part doesn't work in Laravel 5.3.Output is `http://localhost/route/recent/desc` – Peter Chaula Apr 02 '17 at 14:36
0
Route::get('category/{id}/{query}/{sortOrder}', [
    'as' => 'sorting',
    'uses' => 'CategoryController@searchByField'
])->where([
    'id' => '[0-9]+',
    'query' => 'price|recent',
    'sortOrder' => 'asc|desc'
]);

And your url should looks like this: http://category/1/recent/asc. Also you need a proper .htaccess file in public directory. Without .htaccess file, your url should be look like http://category/?q=1/recent/asc. But I'm not sure about $_GET parameter (?q=).

Grzegorz Gajda
  • 2,424
  • 2
  • 15
  • 23