How to pass an optional parameter to a route?

Posted 5 months ago by malhayek

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?}', '[email protected]')
        ->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?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.