Laravel: How to retrieve URL parameters in Blade views

Updated: January 18, 2024 By: Guest Contributor Post a comment

Introduction

Laravel, the popular PHP framework, offers an elegant templating engine known as Blade. Blade templates provide a convenient way to generate HTML for your application, and they can leverage the full power of PHP. One common task you may encounter is the need to access query string parameters in your views. This tutorial will guide you through different methods of retrieving URL parameters directly within Blade views.

What are URL Parameters?

URL parameters are query string values that follow traditional URL paths. They are often used to pass data to the server for processing actions like searches or filtering content. URL parameters are easily recognizable, typically following a question mark (?) in a URL. For instance:

https://www.slingacademy.com/users?search=JohnDoe

Here, search is a URL parameter key with the value JohnDoe. To use these parameters within Laravel’s Blade template, you can access them through various methods described below.

Getting Started with URL Parameters in Blade

Before retrieving URL parameters in your Blade views, you’ll need to make sure that these parameters are being passed correctly from your routes or controllers. Here is how you might pass data from a controller to a Blade view:

{!! htmlspecialchars_decode($example_code) !!}goes here

Passing Data to Views

In your controller, you can use the request() method to access the URL parameters and forward them to the view like this:

public function show(Request $request)
{
    $searchTerm = $request->query('search', 'default');
    // Pass the searchTerm to the view
    return view('user.index', compact('searchTerm'));
}

Here, the query method is used to retrieve the search parameter from the URL, with an optional default value provided. The compact function is then used to simplify passing data to the view. Inside the user.index Blade template, you can display this value like so:

<h3>Results for: {{ $searchTerm }}</h3>

Direct Access in Blade Templates

Sometimes you may want to access the URL parameters directly in the Blade view without passing them from a controller. Laravel allows this using several approaches.

Using Request Helper Function

In the Blade view, you can use the global request() helper function to access the URL parameters, like so:

<div> Search Term: {{ request()->get('search', 'default') }} </div>

Accessing All Query Parameters

If you want to list all of the query parameters, you can do it with the following code:

<ul>
    @foreach(request()->query() as $key => $value)
        <li>{{ $key }}: {{ $value }}</li>
    @endforeach
</ul>

Utilizing Route Model Binding

If you’re using route model binding and you have parameters bound to models, you can inject these into your views just as you would with any other variable:

// UserController.php
use App\Models\User;
// ...

public function show(User $user)
{
    return view('users.show', compact('user'));
}
<!-- users/show.blade.php -->
{{ $user->name }} has an ID of {{ $user->id }}.

Using Blade Components and Services

Another method is leveraging Blade components and service providers. Blade components allow you to create reusable pieces of HTML and functionality, including reading URL parameters:

<x-url-param name="search" />

In a provider, you may set up a method to resolve URL parameters and make them available within components:

public function boot()
{
    \Blade::component('url-param', function ($name, $default = null) {
        return request()->get($name, $default);
    });
}

Above, the \Blade::component method registers a new Blade component that can be used to output a URL parameter.

Security Considerations

Always remember that URL parameters are user input and could be manipulated, posing a security risk if not properly handled.

Proper Escaping

Ensure that you are escaping output using the double curly brace syntax ({{ $variable }}) which will automatically apply PHP’s htmlspecialchars function to avoid XSS attacks.

Validating Input

Furthermore, you should always validate and/or sanitize your URL parameters within your controller before using them in your view. Laravel’s $request->validate() function provides a convenient way to do this.

public function search(Request $request)
{
    $validated = $request->validate([
        'search' => 'required|max:255',
    ]);
    // Use $validated['search'] in the rest of your method
}

This ensures that only valid data is being passed to your views and used in your application.

Conclusion

By utilizing the methods outlined in this tutorial, such as the request() helper function, route model binding, or Blade components, you can efficiently retrieve and safely handle URL parameters in your Laravel Blade views. Remember to always validate and sanitize user-provided data to maintain a secure and reliable application.