How to Use Get Parameters in URL’s Using Laravel

When building web applications, it’s common to pass data through the URL using GET parameters. In Laravel, there are several ways to read and use these parameters.

In this article, we’ll explore four methods for reading parameters from an URL in Laravel.

Method 1: Reading a Parameter From the Query String

A Query string is an optional part at the end of an URL right after the question mark. An example would be http://mydomain.com/books?search=Dune which has a parameter named “search” which contains a value is “Dune”. An URL can also contain multiple values in which case http://mydomain.com/books?search=Dune&page=1

To read a parameter from the query string in Laravel you can use the $request object that Laravel provides. The parameter value can be read either by using $request->input(‘parameter’) or by accessing it as a property like $request->parameter.

// Retrieve a single parameter
$value = $request->input('parameter');

// Another way to retrieve a single parameter
$value = $request->parameter;

Let’s have a look at a full example. First consider this route definition in web.php:

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

Route::get('books/search', [BookController::class, 'searchBook']);

Now lets check out the BookController we’ve assigned to this route. In it’s searchBook method we’ll use the get parameter “term”, as passed in the url, to retrieve a book from an array based on the search term.

This can be done by accessing the $request object like shown below:

app/Http/Controllers/BookController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BookController extends Controller
{
    public function searchBook(Request $request)
    {
        $books = [
            'The Hobbit' => 'J.R.R. Tolkien',
            'Dune' => 'Frank Herbert'
        ];

        echo "The book you searched is written by: " . $books[$request->term] ?? "I don't know this book";
    }
}

In our browser, we can now provide a search term after ?term=.. and see the following output:

Example of a Search Using a GET parameter

Method 2: Getting a Parameter From a Route Segment

Routes are typically defined in app/routes/web.php or app/routes/api.php by any number of calls to the route facade. They offer ways to control which URLs are known and how Laravel responds to URLs.

To define parameters in Laravel routes we use curly braces. These braces indicate where in the URL a parameter value is expected and what the name of the corresponding variable will be.

Here’s an example:

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

Route::get('/say/{parameter}', function ($parameter) {
    dd("The browser says: " . $parameter);
});

To test this in our browser, we can provide any value, such as “HelloThere!”, and the output will be:

Example of Printing a Route Parameter Value as Received by a URL

Method 3: Passing Route Segment Parameters to the Controller

In Laravel applications the route files should contain only a minimal amount of code. For this reason, the Route facade typically passes the request on to a Controller function for further processing.

To pass the values of route parameters to a controller, we use the curly braces syntax in the first parameter of the Route facade call. In the second parameter, we specify the name of the controller and the function that will receive the parameters.

Consider this full example:

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

Route::get('books/{search}', [BookController::class, 'searchBook']);

Note the {search} part, which marks a route segment in the url to contain a dynamic parameter with a specific name.

app/Http/Controllers/BookController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BookController extends Controller
{
    public function searchBook($search)
    {
        $books = [
            'The Hobbit' => 'J.R.R. Tolkien',
            'Dune' => 'Frank Herbert'
        ];

        echo "The book you searched is written by: " . $books[$search] ?? "I don't know this book";
    }
}

In our browser, we can now provide a book as part of the URL instead of the Query String. The output would be:

Example of Using a Route Parameter Value to Search an Array

Method 4: Injecting a Model as a Route Parameter (Route Model Binding)

As described earlier a route facade typically calls a controller with one or more parameters received from the browser. Often times this parameter contains the id of a database record we need to work with. We can do this ourselves or use Route Model Binding.

Route Model Binding in Laravel means a record with an id provided in a route parameter will automatically be injected as an Eloquent Model which the Controller can then use. For this process to work the Controller must type-hint the parameter with the corresponding Model class.

Consider the example code below which uses Route Model Binding to easily retrieve and display a post using minimal code. An example URL we could use would be: https://blog.test/posts/1

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

Route::get('/posts/{post}', [PostController::class, 'show']);
app/Models/Post.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
}
app/Http/Controllers/PostController.php
namespace App\Http\Controllers;
use App\Models\Post;

class PostController extends Controller
{
    public function show(Post $post)
    {
        return view('posts.show', ['post' => $post]);
    }
}
resources/views/posts/show.blade.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Example blog by laracoding.com</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.3/css/bulma.min.css">
</head>
<body>
<section class="hero is-info">
    <div class="hero-body">
        <div class="container">
            <h1 class="title">
                This is an example blog.
            </h1>
            <h2 class="subtitle">
                by laracoding.com
            </h2>
        </div>
    </div>
</section>

<section class="section">
    <div class="container">
        <div class="columns">
            <div class="column is-half">
                <h1 class="title">{{ $post->title }}</h1>
                <h2 class="subtitle">Published: {{ $post->created_at }}</h2>
                <div class="content">
                    {!! $post->content !!}
                </div>
            </div>
        </div>
    </div>
</section>

<footer class="footer">
    <div class="content is-flex-align-items-flex-end mt-auto">
        <div class="container">
            <p>
                Made with ❤ by laracoding.com
            </p>
        </div>
    </div>
</footer>

</body>
</html>

The result then looks like this:

Screenshot of a Browser Showing a Rendered Post

Conclusion

In this article, we covered several methods for handling URL parameters in Laravel applications. We looked at methods for retrieving parameters from the query string, reading them from curly brace-marked route segments in the URL, passing them directly to a controller, and finally we covered auto-injecting a model instance based on a route parameter.

With these tools, you can create build many use cases that use the URL for dynamic behavior in your own web applications. Happy coding!

Johan van den Broek

Johan is the creator of laracoding.com. As a child, he began tinkering with various programming languages, many of which have been long forgotten today. Currently, he works exclusively with PHP and Laravel, and his passion for programming remains to this day.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts