Hello Devs, 

In this tutorial, we will learn Laravel Model Creating Event Example

Creating method sent before records have been created. These are the events that you can use with your Laravel models.

Follow this step-by-step guide below. 


Step 1: Create Item Event

php artisan make:event ItemEvent

app/Events/ItemEvent.php

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\Item;
use Log;

class ItemEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */

    public function itemCreated(Item $item)
    {
        Log::info("Item Created Event Fire: ".$item);
    }
}


Step 2: Register Event

app/Providers/EventServiceProvider.php

<?php

namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{

    /**
     * The event listener mappings for the application.
     *
     * @var array
     */

    protected $listen = [

        'App\Events\Event' => [
            'App\Listeners\EventListener',
        ],
        'item.created' => [
            'App\Events\ItemEvent@itemCreated',
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */

    public function boot()
    {
        parent::boot();
    }
}


Step 3: Create Model

app/Item.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{

    protected $fillable = ['name', 'price'];

    public static function boot() {

	    parent::boot();

	    static::created(function($item) {
	        \Log::info('Item Created Event:'.$item);
	    });

	    static::creating(function($item) {
	        \Log::info('Item Creating Event:'.$item);
	    });
	    
	}
}


Step 4: Add Demo Route

routes/web.php

Route::get('item-created', function(){
    \App\Item::create(['name'=>'demo', 'price'=>200]);
    dd('Item created successfully.');
});

run following example like as bellow :

http://localhost:8000/item-created


storage/logs/laravel.log

[2020-08-28 05:38:18] local.INFO: Item Creating Event:{"name":"demo","price":200}  
[2020-08-28 05:38:18] local.INFO: Item Created Event:{"name":"demo","price":200,"updated_at":"2020-08-28T05:38:18.000000Z","created_at":"2020-08-28T05:38:18.000000Z","id":54}


May this example help you.