I was reviewing a project recently, and I saw a few routes defined like this:
Route::get('show/{type}', Controllers\ReportController::class)
->whereIn('type', array_column(Enums\ReportType::cases(), 'value'))
->name('show');
This code works, but it isn't fully leveraging Laravel's features.
Shortly after PHP 8.1 introduced enums, Laravel continually added first-class support for them in various parts of the framework.
One of those areas was route model binding.
For example, you can now simplify the route to this:
Route::get('show/{type}', Controllers\ReportController::class)
->name('show');
And if you add the enum type hint to the controller method, Laravel will automatically handle the enum validation for you.
public function __invoke(Enums\ReportType $type, ReportRequest $request)
{
// logic omitted
}
This still enforces the same whereIn
logic as the original route, but it does it implicitly following the conventions.
If type
is not a valid value for the ReportType
enum, Laravel will automatically return a 404 response.
It's a small thing, but it all adds up to cleaner code and better maintainability.
Here to help,
Joel
P.S. Want your code reviewed by a team that regularly re-reads the Laravel docs? Make your code shine! Get in touch.