Model Events Example in LARAVEL 10

Spread the love

Hello Guys,

In this post, we delve into Laravel 10 model events with an illustrative example. Learn how to utilize model events in Laravel 10 effectively. If you’re searching for a practical demonstration of an eloquent model event in Laravel 10, you’ve arrived at the right place. We will walk you through the development of model events tailored for Laravel 10. Discover the essential steps required to enhance your knowledge of Laravel 10 model events.

Laravel offers eloquent model events, each serving a unique purpose. These model events can significantly enhance your application. Explore the benefits of Laravel’s expressive model events, which are designed to elevate your development experience.

creating: Call Before Create Record.
created: Call After Created Record.
updating: Call Before Update Record.
updated: Class After Updated Record.
deleting: Call Before Delete Record.
deleted: Call After Deleted Record.
retrieved: Call Retrieve Data from Database.
saving: Call Before Creating or Updating Record.
saved: Call After Created or Updated Record.
restoring: Call Before Restore Record.
restored: Call After Restore Record.
replicating: Call on replicate Record.

Also Read: How to upload Images using LARAVEL 10

When managing a database record, there are instances where it’s essential to include a distinctive identifier or generate a user-friendly slug from the title. It’s crucial to keep these fields up-to-date whenever pertinent events occur, just like when updating records, which requires refreshing the slug and, at times, deleting associated child entries when deleting records. This functionality proves to be highly valuable in scenarios like these.

To provide a clearer understanding of how these model events operate, I’ll present a few notable events, explaining their functionality and practical application.

For a straightforward comprehension of how model events work, we’ll highlight the ‘creating,’ ‘created,’ ‘updating,’ ‘updated,’ and ‘deleted’ events within this example, showcasing the respective outcomes in the log file.

Create a Product Model with events

In this tutorial, we will demonstrate how to create an event-driven product model. Follow the steps below to access and insert the provided code.

Also Read: how to use Cron Job Task Scheduling using LARAVEL 10

app/Models/Product.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Log;
use Str;
   
class Product extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name', 'slug', 'detail'
    ];
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public static function boot() {
  
        parent::boot();
  
        /**
         * Write code on Method
         *
         * @return response()
         */
        static::creating(function($item) {            
            Log::info('Creating event call: '.$item); 
  
            $item->slug = Str::slug($item->name);
        });
  
        /** 
         * Write code on Method
         *
         * @return response()
         */
        static::created(function($item) {           
            /*
                Write Logic Here
            */ 
  
            Log::info('Created event call: '.$item);
        });
  
        /**
         * Write code on Method
         *
         * @return response()
         */
        static::updating(function($item) {            
            Log::info('Updating event call: '.$item); 
  
            $item->slug = Str::slug($item->name);
        });
  
        /**
         * Write code on Method
         *
         * @return response()
         */
        static::updated(function($item) {  
            /*
                Write Logic Here
            */    
  
            Log::info('Updated event call: '.$item);
        });
  
        /**
         * Write code on Method
         *
         * @return response()
         */
        static::deleted(function($item) {            
            Log::info('Deleted event call: '.$item); 
        });
    }
}

Let’s sequentially execute the model methods and analyze the outcomes.

Also Read: How to Get Database Name using Laravel?

Create Record: Creating and Created Event

app/Http/Controllers/ProductController.php
<?php
  
namespace App\Http\Controllers;
  
use App\Models\Product;
use Illuminate\Http\Request;
  
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        Product::create([
            'name' => 'silver',
            'detail' => 'This is silver'
        ]);
  
        dd('done');
    }
}
Output Log File:
[2023-02-15 11:33:30] local.INFO: Creating event call: {"name":"silver","detail":"This is silver"}  

[2023-02-15 11:33:30] local.INFO: Created event call: {"name":"silver","detail":"This is silver","slug":"silver","updated_at":"2023-02-20T16:30:15.000000Z","created_at":"2023-02-20T14:30:15.000000Z","id":5} 

Update Record: Updating and Updated Event

app/Http/Controllers/ProductController.php
<?php
  
namespace App\Http\Controllers;
  
use App\Models\Product;
use Illuminate\Http\Request;
  
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        Product::find(5)->update([
            'name' => 'silver updated',
            'detail' => 'This is silver'
        ]);
   
        dd('done');
    }
}
Output Log File:
[2023-02-15 11:40:06] local.INFO: Updating event call: {"id":5,"name":"silver updated","detail":"This is silver","created_at":"2020-10-20T14:37:26.000000Z","updated_at":"2023-02-15T11:40:06.000000Z","slug":"silver"}  

[2023-02-15 11:40:06] local.INFO: Updated event call: {"id":5,"name":"silver updated","detail":"This is silver","created_at":"2020-10-20T14:37:26.000000Z","updated_at":"2023-02-15T11:40:06.000000Z","slug":"silver-updated"}

Delete Record: Deleted Event

app/Http/Controllers/ProductController.php
<?php
  
namespace App\Http\Controllers;
  
use App\Models\Product;
use Illuminate\Http\Request;
  
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        Product::find(5)->delete();
   
        dd('done');
    }
}
Output Log File:

Also Read: How To Import Excel File Into Database in Python

[2023-02-15 05:20:30] local.INFO: Deleted event call: {"id":5,"name":"silver updated","detail":"This is silver","created_at":"2023-02-15T05:20:30.000000Z","updated_at":"2023-02-15T05:20:30.000000Z","slug":"silver-updated"}  

Now you have the ability to conduct a self-assessment.

Uncover the ultimate insights in our collection, your gateway to the best Laravel blog content.

Leave a Comment