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?
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