How to pass an optional parameter to a route?

Posted 2 months ago by malhayek

I have the following controller


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.

    'prefix' => 'customers',
], function () {
    Route::get('/{term?}', '[email protected]')

    // 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.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up


Reply to

Use Markdown with GitHub-flavored code blocks.