Simplify URL Generation with Laravel's New query() Method

Simplify URL Generation with Laravel's New query() Method

Finding yourself writing repetitive code to build URLs with query parameters? Laravel's new query() method offers a cleaner, more intuitive approach to generating URLs with complex query strings.

Creating URLs with query parameters is a common task in web development, but it can quickly become tedious and error-prone. Laravel has always provided helper functions to build URLs, but the new query() method takes this a step further by offering a dedicated, expressive API specifically for handling query parameters.

Let's see how it works:

// Generate: http://localhost/products?sort=-name
url()->query('products', ['sort' => '-name']);

The query() method accepts a base path as its first argument and an array of query parameters as the second argument. It then combines them to create a complete URL with the parameters properly encoded.

Real-World Example

The query() method shines when working with complex parameter structures. Let's look at some common use cases:

// Simple key-value pairs
// http://localhost/products?sort=-name
url()->query('products', ['sort' => '-name']);

// Arrays as parameters (for filters, columns, etc.)
// http://localhost/products?columns[0]=name&columns[1]=price&columns[2]=quantity
url()->query('products', ['columns' => ['name', 'price', 'quantity']]);

// Overriding existing parameters
// http://localhost/products?sort=-price
url()->query('products?sort=-name', ['sort' => '-price']);

// Appending parameters to existing ones
// http://localhost/products?sort=-name&search=samsung
url()->query('products?sort=-name', ['search' => 'samsung']);

This method is particularly useful when building APIs, dashboards, or any feature requiring sophisticated filtering and sorting capabilities. For example, in a product catalog with filtering and pagination:

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $products = Product::query();
        
        // Apply filters based on request parameters
        if ($request->has('category')) {
            $products->where('category_id', $request->category);
        }
        
        // Apply sorting
        if ($request->has('sort')) {
            $sort = $request->sort;
            $direction = str_starts_with($sort, '-') ? 'desc' : 'asc';
            $column = ltrim($sort, '-');
            $products->orderBy($column, $direction);
        }
        
        $products = $products->paginate(20);
        
        // Generate next page URL with all current filters
        $nextPageUrl = null;
        if ($products->hasMorePages()) {
            $params = $request->query();
            $params['page'] = $products->currentPage() + 1;
            $nextPageUrl = url()->query('products', $params);
        }
        
        return view('products.index', [
            'products' => $products,
            'nextPageUrl' => $nextPageUrl,
            'filterUrl' => function($newParams) use ($request) {
                // Generate URLs for filter controls while preserving other parameters
                $params = array_merge($request->query(), $newParams);
                return url()->query('products', $params);
            }
        ]);
    }
}

This feature is especially valuable when building front-end components that require URLs with dynamic query parameters, such as:

  • Filter and sort controls for tables or lists
  • Pagination links that preserve current filter/sort settings
  • Search forms with multiple optional parameters
  • API endpoints that accept complex filtering options

Using the query() method consistently throughout your application creates a more maintainable and consistent experience for both developers and users. It eliminates common pitfalls like forgetting to encode parameters properly or inadvertently overriding existing query strings.

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter (https://x.com/harrisrafto), Bluesky (https://bsky.app/profile/harrisrafto.eu), and YouTube (https://www.youtube.com/@harrisrafto). It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe