Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

randm's avatar
Level 6

How to pass an optional parameter to a route?

I have the following controller

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Customer;

class CustomersController extends Controller
{
    /**
     * Display a listing of the customers.
     *
     * @return Illuminate\View\View
     */
    public function index($term = null)
    {
        $customers = Customer::search($term)->paginate(25);

        return view('customers.index', compact('customers', 'term'));
    }
}

Then I have the following route.

Route::group([
    'prefix' => 'customers',
], function () {
    Route::get('/{term?}', 'CustomersController@index')
        ->name('customers.customer.index');

    // other routes are removed from simplicity
});

I am expecting that the above would scan the the form-date add/or the URL parameters and sets the matching parameter in the action method. In other words, I am expecting that the $term variable would get set if I go to the following URL http://app.test/customers?term=term

However, my form uses GET method to which generated the following url http://app.test/customers?term=term the $term variable would always be set to NULL

How can I correctly pass this optional param to the action method?

0 likes
3 replies
Cronix's avatar
Cronix
Best Answer
Level 67

I think you're misunderstanding what ? means to the router. The router only deals with url segments, not query strings. Query string parameters (?term=term) are available to the Request object (which you'd use in the controller (etc) to access), but they are not dealt with at the router level.

'/{term?}'

What that is saying is that the term segment is optional. Since it's within the "customers" prefix, it would mean that /customers/this-segment-is-optional would work whether or not something appears there in the 2nd segment. If the segment is not included, then it would default to null because you have $term = null in the index method. If it was included, then in the controller $term would be whatever the 2nd segment was, or "this-segment-is-optional" in my example.

https://laravel.com/docs/5.7/routing#parameters-optional-parameters

2 likes
randm's avatar
Level 6

@Cronix thanks for explaining it.

I am not sure why the router does not deal with the query-parameter. I feel that it should be. The router should scan the form-data with in the request and also the query parameter and set the variable accordingly.

It is what it is I guess

jlrdw's avatar

Jumping jahosafats

https://en.m.wikipedia.org/wiki/Query_string

The values are there in the request object.

Query string parameters and passing parameters in the router are two different Worlds, yet serve the same purpose.

Just handled a little different.

Please or to participate in this conversation.