Laravel 11 Model Events Example Tutorial

By Hardik Savani April 16, 2024 Category : Laravel

In this post, I will show you an example of Laravel 11 model events. Laravel 11 provides us with retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, trashed, forceDeleting, forceDeleted, restoring, restored, and replicating model events to work with Eloquent models.

Laravel provides a list of Eloquent model events, and each model event has its own function. It's very helpful. I love Laravel Eloquent model events.

  • creating: Call Before Create Record.
  • created: Call After Created Record.
  • updating: Call Before Update Record.
  • updated: Class After Updated Record.
  • saving: Call Before Creating or Updating Record.
  • saved: Call After Created or Updated Record.
  • deleting: Call Before Delete Record.
  • deleted: Call After Deleted Record.
  • trashed: Call When Trash Record.
  • forceDeleting: Call Before Force Delete Record with SoftDelete.
  • forceDeleted: Call After Force Delete Record with SoftDelete.
  • retrieved: Call Retrieve Data from Database.
  • restoring: Call Before Restore Record.
  • restored: Call After Restore Record.
  • replicating: Call on replicate Record.

Sometimes, we need to generate a slug before creating a new post, or we need to send an email notification after creating a new post, or when deleting a post, we need to send a notification. At this time, we can use model events to do this task automatically using Laravel Eloquent.

We can review a simple example with the Post model. We will write creating, created, updating, updated, and deleted events on the Post model. So, let's see the example code below:

laravel 11 model events

Create Post Model with events

Here, we will create a Post model with events. so let's create and put bellow code:

app/Models/Post.php

<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'title', 'slug', 'body'
    ];

    /**
     * The "booted" method of the model.
     */
    protected static function booted(): void
    {
        /**
         * Call Before Post Create
         */
        static::creating(function (Post $post) {
            info('Creating event call: '.$post); 

            $post->slug = Str::slug($post->title);
        });

        /**
         * Call After Post Create
         */
        static::created(function (Post $post) {

            // SendEmailToAdmin - You can write logic

            info('Created event call: '. $post); 
        });

        /**
         * Call Before Post Update
         */
        static::updating(function (Post $post) {
            info('Updating event call: '.$post); 

            $post->slug = Str::slug($post->title);
        });

        /**
         * Call After Post Update
         */
        static::updated(function (Post $post) {
            
            // SendEmailToAdmin - You can write logic

            info('Updated event call: '. $post); 
        });

        /**
         * Call Before Post Delete
         */
        static::deleting(function (Post $post) {
            info('Deleting event call: '.$post);
        });

        /**
         * Call After Post Delete
         */
        static::deleted(function (Post $post) {
            
            // SendEmailToAdmin - You can write logic

            info('Deleted event call: '. $post); 
        });
    }
}

Now here, we will simply call one by one model method and let's see output:

Create Record: Creating and Created Event

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $post = Post::create([
            'title' => 'Laravel 11 CRUD Application',
            'body' => 'Laravel 11 CRUD Application Body'
        ]);
  
        dd($post->toArray());
    }
}

Output Log File:

[2024-04-06 16:49:24] local.INFO: Creating event call: {"title":"Laravel 11 CRUD Application","body":"Laravel 11 CRUD Application Body"}  
[2024-04-06 16:49:24] local.INFO: Created event call: {"title":"Laravel 11 CRUD Application","body":"Laravel 11 CRUD Application Body","slug":"laravel-11-crud-application","updated_at":"2024-04-06T16:49:24.000000Z","created_at":"2024-04-06T16:49:24.000000Z","id":2}  

Update Record: Updating and Updated Event

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $post = Post::find(1)->update([
            'title' => 'Laravel 11 CRUD Application UP',
            'body' => 'Laravel 11 CRUD Application Body UP'
        ]);
  
        dd($post);
    }
}

Output Log File:

[2024-04-06 16:51:54] local.INFO: Updating event call: {"id":1,"title":"Laravel 11 CRUD Application UP","slug":"laravel-11-crud-application","body":"Laravel 11 CRUD Application Body UP","created_at":"2024-04-06T16:46:29.000000Z","updated_at":"2024-04-06T16:46:29.000000Z"}  
[2024-04-06 16:51:54] local.INFO: Updated event call: {"id":1,"title":"Laravel 11 CRUD Application UP","slug":"laravel-11-crud-application-up","body":"Laravel 11 CRUD Application Body UP","created_at":"2024-04-06T16:46:29.000000Z","updated_at":"2024-04-06T16:51:54.000000Z"}   

Delete Record: Deleted Event

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $post = Post::find(1)->delete();
  
        dd($post);
    }
}

Output Log File:

[2024-04-06 16:54:02] local.INFO: Deleting event call: {"id":1,"title":"Laravel 11 CRUD Application UP","slug":"laravel-11-crud-application-up","body":"Laravel 11 CRUD Application Body UP","created_at":"2024-04-06T16:46:29.000000Z","updated_at":"2024-04-06T16:51:54.000000Z"}  
[2024-04-06 16:54:02] local.INFO: Deleted event call: {"id":1,"title":"Laravel 11 CRUD Application UP","slug":"laravel-11-crud-application-up","body":"Laravel 11 CRUD Application Body UP","created_at":"2024-04-06T16:46:29.000000Z","updated_at":"2024-04-06T16:51:54.000000Z"}  

Now you can check from your end.

I hope it can help you...

Shares