Things to know in Laravel : chapter two

Introduction

In previous article, we discussed about laravel using Doctrine\Common\Inflector\Inflector to have functions like str_plural()  & str_singular() . Today we are going to talk about laravel implicit model binding.

Getting started

We have said many times that laravel helps us speed up our development process. This article is about one of those things. “Laravel implicit model binding”.

When we normally use resource controller of laravel or any other ways. This is what we normaly do :

findOrfail() function will check if the id exist then return the instance otherwise return 404 status.

This is normally what we do. You see we are using findOrfail method redundantly. But what if there was a way to doing so without having to write that line of code. Fortunately, there is and we’re going to elaborate just about that.

Following this approach, it will be cleaner and code will be reduced. All we have to do is inject our model in the function.

This way, you don’t have to use findOrFail in every functions. The parameter (User $user) will check if  the id is an instance of our User model or not.

To inject the model into the resource controller on creation, you can enter the command :

php artisan make:controller UserController -r -m User

User Model will be automatically injected to the resource controller.

Happy coding 🙂

 

Sharing is caring!

Related Post