Sling Academy
Home/PHP/How to Get and Parse Query String in Laravel

How to Get and Parse Query String in Laravel

Last updated: January 18, 2024

Introduction

Working with web applications often requires dealing with HTTP requests and their associated data. In Laravel, one common task is to retrieve and parse query string parameters from the URL. Query strings are a fundamental part of the web as they provide a way to pass data between the server and client through the URL.

In this detailed guide, we’ll dive into how to get and handle query strings in Laravel. By the end, you’ll be familiar with several methods to retrieve query parameters, apply validation, and more – all with the elegance that Laravel provides.

What is a Query String?

A query string is a part of a URL that assigns values ​​to specific parameters. It is introduced by a question mark (?) and followed by a series of key-value pairs, each separated by an ampersand (&). For example, in the URL http://example.com/posts?search=laravel&page=2, the query string is search=laravel&page=2.

Retrieving the Entire Query String

Let’s start with getting the full query string. In Laravel, you can use the request helper or the Request facade.

{{ $queryString = request()->getQueryString(); }}
{{ $queryString = \\Illuminate\\Support\\Facades\\Request::getQueryString(); }}

This provides the raw query string, which you may not require often, but it’s good to know it’s there.

Accessing Individual Query Parameters

If you are interested in specific parameters, you can retrieve them by their keys:

{{ $searchTerm = request()->query('search'); }}
{{ $pageNumber = request()->query('page', 1); }}

In the above example, the second parameter passed to the query method is a default value that will be used where the ‘page’ parameter is not present in the URL.

Checking for Query Parameter Existence

{{ if (request()->has('search')) { }}
  // The 'search' parameter is present in the query string
{{ } }}

You can also use the filled method to check if a parameter is present and not empty:

{{ if (request()->filled('search')) { }}
  // The 'search' parameter is present in the query string and not empty
{{ } }}

Working with Multiple Query Parameters

To retrieve multiple parameters at once, you can pass an array to the query method:

{{ $parameters = request()->query(['search', 'page']); }}

Laravel returns an associative array with the keys representing the parameter names and the values their corresponding query string values.

Validating Query Parameters

Laravel’s validation functionality can also be applied to query string parameters. Here’s how you can use the validate method within a controller:

{{ $validated = request()->validate([ }}
  {{ 'search' => 'required|string|max:255', }}
  {{ 'page' => 'integer' }}
{{ ]); }}

If validation fails, Laravel automatically redirects the user back to the previous page and flashes error messages to the session. For API endpoints, it typically sends back a JSON response with validation errors.

Default Values for Query Parameters

If you want to provide a default value for a query parameter in case it’s not in the URL, you can pass it as the second argument of the query method:

{{ $sortOrder = request()->query('sort', 'asc'); }}

Conditional Clauses With Query Parameters

Laravel allows you to conditionally manipulate queries based on query string parameters.

{{ $posts = \\App\\Models\\Post::query(); }}
{{ if (request()->filled('search')) { }}
  {{ $posts->where('title', 'like', '%' . request()->query('search') . '%'); }}
{{ } }}
{{ $posts = $posts->paginate(request()->query('page', 1)); }}

This is especially useful when building more dynamic applications where users can filter results based on URL parameters.

Tips and Best Practices

  • Always validate query parameters, especially when using them in database queries to protect against SQL injection attacks.
  • Use Laravel’s route() helper function to generate URLs with query strings attached.
  • Remember to encode query parameters when constructing URLs manually to avoid issues with special characters.
  • Be mindful of exposing sensitive data in query strings since URLs can be logged or shared.

We’ve covered the basics and some best practices for dealing with query string parameters in Laravel. It’s a powerful framework that offers a lot of functionality to make this common task elegant and secure.

Next Article: How to extract request headers in Laravel

Previous Article: Lifecycle of a Laravel request: Explained with examples

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array