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?

3 Answers 3

18

if you have other parameters in url you can use;

request()->fullUrlWithQuery(["sort"=>"desc"])
Sign up to request clarification or add additional context in comments.

Comments

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']);

6 Comments

Ok. So, how do i call this from my view?
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()
The thing is that i was doing <a href={{url('route_url'}}></a> this. I guess now i can't do that.
You should still be able to do that, I've updated my answer with an example for generating URLs with query strings
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
|
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=).

1 Comment

You misunderstood my question. I get it what you're saying. But i want to do that with query strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.