Skip to content

Instantly share code, notes, and snippets.

@jasonlbeggs
Created March 6, 2021 00:14
Show Gist options
  • Save jasonlbeggs/581ca538204c593fa56a7859a893b48f to your computer and use it in GitHub Desktop.
Save jasonlbeggs/581ca538204c593fa56a7859a893b48f to your computer and use it in GitHub Desktop.

Laravel booted() Model Method

Laravel's new(ish) booted() model method and PHP arrow functions can (subjectively) really cleaned up these little model event listeners!

<?php

// ...

class Team extends Model
{
    // Before
    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($model) {
            $model->uuid = Str::uuid()->toString();
        });
    }
    
    // After
    protected static function booted()
    {
        static::creating(fn ($model) => $model->uuid = Str::uuid()->toString());
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment