Home » Php » php – Laravel 5.1 add Query strings in url

php – Laravel 5.1 add Query strings in url

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’ve declared this route:

Route::get('category/{id}{query}{sortOrder}',['as'=>'sorting','uses'=>'[email protected]'])->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?

How to&Answers:

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

Answer:

if you have other parameters in url you can use;

request()->fullUrlWithQuery(["sort"=>"desc"])

Answer:

Route::get('category/{id}/{query}/{sortOrder}', [
    'as' => 'sorting',
    'uses' => '[email protected]'
])->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=).