How to Generate Route with Query String in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hey Folks,

Now, let's see post of how to generate route with query string in laravel. This post will give you a simple example of laravel link with query string. We will use laravel query string route. step by step explain laravel add query string to url. So, let's follow a few steps to create an example of laravel url with query string.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

In Laravel, you can generate a route with a query string using the route() function and passing an array of query parameters as the second argument. Here is an example:

Example:

/* Define a route in your routes/web.php file */

Route::get('/products', 'ProductController@index')->name('products.index');

/* Generate a route with a query string using the route() function */

$url = route('products.index', ['category' => 'electronics', 'sort' => 'price']);

In the above example, we defined a route for the index method of the ProductController that handles a GET request to the /products URL. We named this route products.index.

To generate a URL with a query string for this route, we use the route() function and pass the name of the route (products.index) as the first argument. We also pass an array of query parameters as the second argument, where the keys are the names of the query parameters and the values are the values we want to set for them.

In this example, the generated URL will be /products?category=electronics&sort=price.

I hope it can help you...

Tags :
Shares