Implicit Route Model Binding in Laravel 5.2

This is a series of posts that showcase new features and aha moments in Laravel 5.2

1. Implicit Route Model Binding

2. Simplified Eloquent Global Scopes

3. Append Scheduled Tasks Output

4. Form Array Validation

5. Middleware Groups

6. Auth Scaffolding

7.  Api Rate Limiting

8. More helper functions

Laravel 5.2 comes with a new feature called Implicit Model Binding.

Laravel 5.1 already gave us the ability to bind Models to routes but we had to do it manually by calling the Route::model method in the route service provider  to tell Laravel to inject the Model instances in our route definition.

Laravel 5.2 removes that stress by automatically injecting the Model instance based on the route parameter like so:

AppTask is our Model.

Laravel automatically injects the model when the route parameter => task matches the route closure or controller method’s corresponding variable name => $task.

So we can also do this in our route:

Then in TaskController.php, we will have the index method like so:

It’s that simple!.

In Laravel, it actually performs a findOrFail operation in the background like so:

This is actually very handy when writing simple APIs.

With few lines of code like this, your API can be ready in minutes fetching data and returning to consumers.


Please, if you have any questions or observations, let me know in the comments section :smile:



Food Ninja, Code Slinger, Technical Trainer, Accidental Writer, Open Source Advocate and Developer Evangelist.