Laravel Model Observers Tutorial: Complete Guide

If you listen to many events on a given model, you may use observers to group all of your listeners into a single class.  Laravel does not include any default directory for observers, so you may create any folder you like to house your observer classes.

Laravel Model Observers

Observers in Laravel are classes with method names that reflect the Eloquent events you wish to listen for. Each of these methods receives the model as their only argument.

We are going to understand the Model Observers with an example. So let’s get started.

Step 1: Configure the Laravel.

Go to your preferred folder and hit the following command.

composer create-project laravel/laravel --prefer-dist Observer

Now, set up the database in the .env file.

We are going to see the Observer using an add item example. So we need to make three files.

  1. Model File
  2. Controller File
  3. Migration File

So let us create one by one.

php artisan make:model Item -m

The above command will create a Model as well as a migration file.

Now, we need to make a controller file.

php artisan make:controller ItemController

Now, add the schema to the migration file.

  /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }

Now, go to the terminal and hit the following command.

php artisan migrate

It will create the table in the database.

Now we need to make two routes in the web.php file.

// web.php

Route::get('item', 'ItemController@create');
Route::post('item', 'ItemController@store');

Also, we need to make these two functions in the ItemController.php file.

// ItemController.php

public function create()
{

}
public function store(Request $request)
{
        
}

Step 2: Make View File And Store The Data.

First, we are going to make that view file.

<!doctype html>
<html>
   <head>
      <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css" />
   </head>
   <body>
	<div class="container">
         <br/>
	  <div class="panel panel-primary">
	   <div class="panel-heading">
	     Add Item
	   </div>
	   <div class="panel-body">
             <form method="post" action="{{ route('item.store') }}">
                {{csrf_field()}}
		 <div class="form-group">
		   <label class="col-md-4">Item Name</label>
		     <input type="text" class="form-control" name="name"/>
		  </div>
		   <div class="form-group">
		     <label class="col-md-4">Item Price</label>
			<input type="text" class="form-control" name="price"/>
		    </div>
		    <div class="form-group">
			<button type="submit" class="btn btn-primary">Add</button>
		    </div>
		</form>
	    </div>
         </div>
      </div>
   </body>
</html>

Now, Change in the ItemController.php file.

public function create()
{
   return view('create');
}

Also, we are going to store the data.

// ItemController.php

public function store(Request $request)
{
    $item = new Item;
    $item->name = $request->get('name');
    $item->price = $request->get('price');
    $item->save();

    return 'Store the data';
}

Next, go to http://localhost:8000/item and fill in 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 make the name into the upper case, 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 the following types of Model Events available in Laravel Doc.

Eloquent models shoot several events, allowing you to hook into the next points in a model’s lifecycle: retrievedcreatingcreatedupdatingupdatedsavingsaveddeletingdeletedrestoringrestore

We will use one of the above’s events to turn the name letters into uppercase without writing any logic into the controller file.

Now, go to the app  >>  Providers  >>  AppServiceProvider.php file and add the following code.

// AppServiceProvider.php

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        \App\Item::creating(function($model){
            $model->name = strtoupper($model->name);
        });
    }

Here at the time of the creation of the model, we are telling the Laravel that please convert all letters of the name attribute to capital. So here, we have used the Model Events to complete our task.

We can also create the dedicated class that provides the method, and then in that method, we will use the logic to convert the letters.

Step 4: Create Service Provider for the Observers.

Make the service provider for the following command.

php artisan make:provider ItemModelServiceProvider

Register this service provider into the Laravel App. Go to the config  >>  app.php file. Add the following code.

 'providers' => [
   App\Providers\ItemModelServiceProvider::class,
];

Now, we can not create the Observer through the command line, so we will create a directory inside the app folder called Observers. In that folder, we need to create the ItemObserver.php file.

<?php

namespace App\Observers;
use App\Item;

class ItemObserver
{
   public function creating(Item $item)
   {
      $item->name = strtoupper($item->name);
   }
}

Now, we also need to register this observer inside the ItemModelServiceProvider.php file.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ItemModelServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        \App\Item::observe(\App\Observers\ItemObserver::class);
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Now, again try to save the data, and it works. We can easily see that name is upper case.

So that is how we can use the Model Observers. The general use case is maybe when we have cached the data, but when the data is updated, we need to flush the cache and rebuild the cache for the correct data.

That’s it for the Laravel model observers tutorial.

5 thoughts on “Laravel Model Observers Tutorial: Complete Guide”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.