Engineering note · Laravel
Route Model Binding with Custom Query Constraints
By Farah Jokhio Published
Route model binding with query constraints is used to ensure that only specific models are bound, this will optimize both performance and security.
// Define a route with custom model binding constraint
Route::get('user/{user}', [UserController::class, 'show'])
->where('user', '^[0-9]+$');
// Define a custom model binding logic in RouteServiceProvider
public function boot()
{
parent::boot();
Route::bind('user', function ($value) {
return User::where('id', $value)
->where('status', 'active')
->firstOrFail();
});
}
Defines a route with a custom constraint ensuring the {user} parameter only matches numeric values.Route::get('user/{user}', [UserController::class, 'show'])->where('user', '^[0-9]+$'):
Customizes how the user parameter is resolved. This example adds a constraint that the user must be active, enhancing security and data integrity.Route::bind('user', function ($value) { ... }):
More engineering notes
Sanitize Input to Prevent SQL Injection
Always use Eloquent ORM or Laravel's query builder to interact with the database, which automaticall...
Use Blade Layouts for Consistency
Utilize Blade layouts to maintain consistent structure and reduce redundancy across your application...