PHP code example of mvanduijker / laravel-transactional-model-events

1. Go to this page and download the library: Download mvanduijker/laravel-transactional-model-events library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mvanduijker / laravel-transactional-model-events example snippets




class MyModel extends Model
{
    use TransactionalAwareEvents;
}



/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'eloquent.afterCommit.created: App\Models\Shipment' => [
        'App\Listeners\SendShipmentNotification',
    ],
];




class PictureFile extends Model
{
    use TransactionalAwareEvents;
    
    public static function boot()
    {
        parent::boot();
        
        static::registerModelEvent('afterCommit.deleted', function ($model) {
            if (Storage::exists($model->file)) {
                Storage::delete($model->file);            
            }
        });
    }
}



class PictureFile extends Model
{
    use TransactionalAwareEvents;
    
    protected $dispatchesEvents = [
        'afterCommit.created' => PictureFileCreated::class,
        'afterCommit.deleted' => PictureFileDeleted::class,
    ];
}



class PictureFileObserver
{
    public function afterCommitDeleted(PictureFile $model)
    {
        if (Storage::exists($model->file)) {
            Storage::delete($model->file);            
        }
    }
}



namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        PictureFile::observe(PictureFileObserver::class);
    }
}