Skip to content

All topics  /  Laravel

Laravel Model Creating Event Example

Laravel ·

Teams applying “Laravel Model Creating Event Example” in a production project can use innovation adoption curve to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with the official Laravel website and test it against the project’s actual database and runtime.

In this example,I will learn you how to use model creating event in laravel.you can easy and simply use model creating event in laravel.

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

Models events are simpy hooks into the important points of a model's lifecycle which you can use to easily run code when database records are created.

Step 1: Create Item Event


In this step we will create event for Item model. So simply run bellow command and create event for Item.

php artisan make:event ItemEvent

Ok, now you have new file in Events folder. So you can see ItemEvent.php file in your Events directory and put bellow code on that file.

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

Now, we have to register following events on EventServiceProvider.php file. So let's simply open that file and put like as bellow code:

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

Now we will create morel for "items" table. So just simple create Item.php file and also add events code on boot method:

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

Now we will test following all event like create, update and delete model task. So just simple add following routes:

routes/web.php

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

Ok, now we are ready to run following example like as bellow :

http://localhost:8000/item-created

Then you will find in your log file like as bellow:

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}

It will help you...