0
0
Laravelframework~5 mins

Query parameters in Laravel

Choose your learning style9 modes available
Introduction

Query parameters let you send extra information in a URL to control what data you get back. They help make your web app respond to user choices.

When filtering a list of products by category or price on an online store.
When searching for users by name or email in an admin panel.
When paginating results to show a specific page number.
When sorting data by date or popularity.
When passing optional settings or flags to a route.
Syntax
Laravel
use Illuminate\Http\Request;

Route::get('/search', function (Request $request) {
    $term = $request->query('term');
    // Use $term to filter results
});
Use $request->query('key') to get a query parameter value safely.
You can provide a default value like $request->query('key', 'default') if the parameter is missing.
Examples
This gets the 'category' parameter from the URL like ?category=books.
Laravel
use Illuminate\Http\Request;

Route::get('/products', function (Request $request) {
    $category = $request->query('category');
    return "Category: $category";
});
This gets the 'page' parameter or uses 1 if none is given.
Laravel
use Illuminate\Http\Request;

Route::get('/users', function (Request $request) {
    $page = $request->query('page', 1);
    return "Page number: $page";
});
This reads the search term from the URL query.
Laravel
use Illuminate\Http\Request;

Route::get('/search', function (Request $request) {
    $term = $request->query('term');
    return "Searching for: $term";
});
Sample Program

This route reads two query parameters, 'color' and 'size', and shows their values or defaults if missing.

Laravel
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/filter', function (Request $request) {
    $color = $request->query('color', 'any');
    $size = $request->query('size', 'all');
    return "Filter applied: color=$color, size=$size";
});
OutputSuccess
Important Notes

Query parameters are part of the URL after the ? symbol, like ?color=red&size=large.

Always validate or sanitize query parameters before using them to avoid security issues.

Laravel's Request object makes it easy to access query parameters with query().

Summary

Query parameters send extra info in URLs to control data returned.

Use $request->query('key') to get them in Laravel routes.

Provide default values to handle missing parameters gracefully.