In Laravel, events are a way to implement the observer pattern. They allow you to broadcast and listen for events within your application. By using events, you can decouple different parts of your application and make them more maintainable and testable.
Create Product Model with events
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);
});
}
}
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'
]);
}
}
Update Record:
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');
}
}
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');
}
}