Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the : in a Laravel route parameter?

In the codebase I am working on, the routes use route parameters. I noticed something interesting though. It looks like {flight:id}.

Route:

Route::get('/flight/{flight:id}', [FlightController::class, 'book'])->where('flight','[0-9]+');

I do not know what the colon :id does. Is this Laravel functionality?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the controller, the book method does not query the model. It appears to just have the flight passed to it. Where is the model accessing the database?

Controller:

public function book($domain, Flight $flight)
    {

        return view('flights.booked',[
            'flight' => $flight,
        ]);

    }

In every example I could find online, the controller still accessed the model with a passed id.

>Solution :

flight/{field:id} is Laravel functionality that tells Laravel how to construct the associated Flight $flight Model during Route-Model Binding.

By default, it uses the Primary Key of the Model (which is typically id), so if your Model is using id, you can just do flight/{flight} and Flight $flight will work.

If you want to use something else, like a uuid or slug, you’d modify it to flight/{flight:uuid} or flight/{flight:slug}, and Flight $flight will be constructed based on the supplied key and column value from your Database.

Documentation can be found here:

https://laravel.com/docs/10.x/routing#customizing-the-key

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading