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.