Laravel - Updating Model Fields Before Save
1 min read

Laravel - Updating Model Fields Before Save

Hooking into a event in a model's lifecycle is a powerful approach in Laravel, especially if you need to calculate a fields value prior to saving it to the database.

You can accomplish this by utilizing the laravel events in a models boot method. These list of events include retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored, and replicating.

Let's say we have a model called Character, which has several stats on the model, such as strength, intelligence, and agility. If we wanted to also have a overall stat that was a average of the above stats, we could use the creating and updating events on the model to calculate this stat prior to saving the model to the database.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Character extends Model
{
  use HasFactory;

  protected static function booted()
  {
  	// if creating or updating, calculate overall stat
    self::creating(function ($model) {
      $model->overall_score = $model->calculateOverallStat($model);
    });
    self::updating(function ($model) {
      $model->overall_score = $model->calculateOverallStat($model);
    });
  }

  private function calculateOverallStat($character)
  {
    $stats = [
      $character->strength,
      $character->intelligence,
      $character->agility
    ];
    return array_sum($stats) / count($stats); // return average
  }
}