Steps To Install And Use Laravel Model Observer Step 1 : Install Fresh Laravel Project
composer create-project –prefer-dist laravel/laravel observer
Now, set up the database in the .env file.
We are going to see the Observer using an add Category example. So we need to make three files.
1. Model File
2. Controller File
3. Migration File
So let us create.
php artisan make:model Category -mc
Above command will create Model , Controller as well as Migration file.
Now, add the schema in the database/2020_01_09_090050_ create_categories_table migration file.
Now, go to the terminal and hit the following command. php artisan migrate We need to make routes in the routes/web.php file
Also, we need to make functions in the App/Http/Controllers/Category
No Need To Write Logic Into Category Controller. All The Logic Is Written Into App/Category.php Model file.
Step 2 : Make View File And Store The Data.
First, we are going to make view file Into resources/Views/create_category.
Next, go to the localhost and create a category and fill the form values and submit the form. It will store the data.
Step 3: Why we want to use Model Observer.
Now, suppose, if we want to concatenate the string with category name, but we do not want to write the logic or function in the controller then, we can use the Model Events. It will fire automatically when the new record is created or updated or deleted. There are following types of Model Events available in Laravel Doc
Step 4: Create Service Provider for the Observers.
Make the service provider for the following command.
php artisan make:provider CategoryModelServiceProvider Register this service provider into the Laravel App. Go to the config/app.php file. Add the following code.
Now run the following command it will create App/Observers/CategoryObserver file. php artisan make:observer CategoryObserver Then write function of observer like this.
Now, we also need to register this observer inside the App/Providers/CategoryModelService
Now, again try to save the data and it works. We can easily see that name is concatenate with static string. So that is how we can use the Model Observers.
Finally, Laravel Model Observers Tutorial With Example is over.