Model injection

With the help of an ID, we obtain an object in the action method of a controller.

Automatic injection

Previously: We had to search for the ID in the database to obtain the object.

How to use:
public function show(Product $product)
{
return view('products.show', compact $product;
}

By default, Laravel looks for the id column, but you can customize it using the whole Model with all it's attributes


In Laravel 10, Model Injection refers to automatically resolving Eloquent models in your controller methods or route closures by type-hinting them in function parameters.

Laravel will retrieve the model based on the route parameter and inject it into the method.

Basic Example: Route Model Binding

Instead of manually querying the database, Laravel can automatically fetch a model instance when defining routes.

Route::get('/product/{product}', function (Product $product)
{
return response()->json($product);
});

Dependency Injection with Model Injection

You can also combine dependency injection with model injection:

see here how to validate first
public function update(Request $request, Product $product)
{

$validatedName = $request->validate(['name' => 'string']);


$product = new Product

$product->name = $validatedName;

$product->save();

return view('products.index', compact $product;

});

Model Injection in Laravel 10 helps Laravel code by automatically retrieving model instances from route parameters.
It works with Route Model Binding, Custom Keys, and Dependency Injection, making controllers and routes cleaner and more efficient.