Tryst with Laravel – Exploring Eloquent Model Events
Tushar Bohra
December 29, 2017

Events provide a simple architecture and better code organisation. They open up a whole new dimension of interaction with the application code.

 

In Laravel, we have Eloquent model events which are fired when we perform some operation on the model.

 

For simpler understanding I usually classify them into two categories-

Before action events

  • Creating/Updating/Saving
  • These are fired up before the action is completed.
  • Use them to make any update on the model before the action is performed and the model persists in the database.

After action events

  • Created/Updated/Saved
  • These are fired up after the action is completed.
  • Use this to make any update on some other model, that should be updated if the original model is updated.

 

Eg. System for army promotions

There are two models Army and ArmySalary.

Suppose one officer’s info is update and they are promoted. We would want their title to change according to the new designation. Both of the information is in the same model. The title is dependent on the designation. We will call the updating/saving event so that the system checks the designation and updates the title before the model is persisted.

public function updating(Army $army)
	{
		$army->title =  self::getDesignationTitle($army->designation);
	}

 

 

When the designation changes, we would want the salary to be updated as well. We’ll use the saved/updated event to update the salary based on the designation of the officer. Here we’ll use the after events (saved/updated).

public function updated(Army $army)
	{
		$army->army_salary->updateSalary();
	}