Use Model Events in Laravel 8.x & Upper

Hi artisans, today I’m going to share how to use model events in Laravel. I’m testing on Laravel 8.9.0. Let’s get started:

Table of Contents

  1. Model Events
  2. Create Model, Migration & Controller
  3. Define Events in Model
  4. Usage

Model Events

Have a look at the model events and their call time:

  • creating – call before creating a record
  • created: Call after creating a record
  • updating: Call before updating a record
  • updated: Class after updating a record
  • deleting: Call before deleting a record
  • deleted: Call after deleting a record
  • retrieved: Call after getting data from the database
  • saving: Call before creating or updating a record
  • saved: Call after creating or updating a record
  • restoring: Call before restoring a record
  • restored: Call after restoring a record
  • replicating: Call on replicate record

Create Model, Migration & Controller

Create a model Book with migration & controller:

php artisan make:model Book -mc

Open the migration file and update up() function like:

timestamp_create_books_table.php
public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('author');
        $table->timestamps();
    });
}

Now migrate the migration:

php artisan migrage

// drop all tables and migrate
php artisan migrate:fresh

Define Events in Model

Open the Book model and define events like:

Book.php
<?php

namespace App\Models;

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

class Book extends Model
{
    use HasFactory;

    /**
     * Boot
     */
    public static function boot()
    {
        parent::boot();

        /**
         * Event: creating
         */
        static::creating(function ($item) {
            Log::info('Creating book: ' . $item);
        });

        /**
         * Event: created
         */
        static::created(function ($item) {
            Log::info('Created book: ' . $item);
        });

        /**
         * Event: deleted
         */
        static::deleted(function ($item) {
            Log::info('Deleted book: ' . $item);
        });
    }
}

I’ve set creating, created and deleted events only. You can set more events.

Usage

We’ve defined 3 events. Now let’s try to call the events. Open BookController and paste this code:

BookController.php
<?php

namespace App\Http\Controllers;

use App\Models\Book;
use Illuminate\Http\Request;

class BookController extends Controller
{
    /**
     * create
     */
    public function create()
    {
        $book = new Book();
        $book->name = "Book 1";
        $book->author = "Author 1";
        $save = $book->save();

        dd($save);
    }

    /**
     * delete
     */
    public function delete($id)
    {
        $delete = Book::destroy($id);

        dd($delete);
    }
}

Open routes/web.php and add these routes:

web.php
use App\Http\Controllers\BookController;

// books
Route::group(['prefix' => 'books'], function () {
    Route::get('create', [BookController::class, 'create']);
    Route::get('delete/{id}', [BookController::class, 'delete']);
});

Now run the project, visit routes & see logs. Logs location is storage/logs/laravel.logs.

/books/create: The logs look like:

[2020-11-04 04:54:56] local.INFO: Creating book event: {"name":"Book 1","author":"Author 1"}
[2020-11-04 04:54:56] local.INFO: Created book event: {"name":"Book 1","author":"Author 1","updated_at":"2020-11-04T04:54:56.000000Z","created_at":"2020-11-04T04:54:56.000000Z","id":1}

/books/delete/1: The logs look like:

[2020-11-04 04:55:16] local.INFO: Deleted book event: {"id":1,"name":"Book 1","author":"Author 1","created_at":"2020-11-04T04:54:56.000000Z","updated_at":"2020-11-04T04:54:56.000000Z"}
That’s it. Thanks for reading. ?