Skip to content

Instantly share code, notes, and snippets.

@simonhamp simonhamp/BaseModel.php
Last active Mar 25, 2020

Embed
What would you like to do?
Eloquent: Simple Model Event Handling
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model
{
/**
* Override the default boot method to register some extra stuff for every child model.
*/
protected static function boot()
{
static::created(function ($model) {
return $model->wasCreated();
});
static::creating(function ($model) {
return $model->beingCreated();
});
parent::boot();
}
/**
* Stub 'created' event handler.
*/
public function wasCreated()
{
// Override me as necessary
}
/**
* Stub 'creating' event handler.
*/
public function beingCreated()
{
// Override me as necessary
}
}
<?php
namespace App;
class MyModel extends BaseModel
{
public function wasCreated()
{
// Do something here
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
/**
* Override the default boot method to register some extra stuff.
*/
protected static function boot()
{
// Register event handlers here!
static::creating(function ($model) {
// Do something before saving
});
static::created(function ($model) {
// Do something after saving
});
parent::boot();
}
}
@simonhamp

This comment has been minimized.

Copy link
Owner Author

simonhamp commented Jan 17, 2018

These are a bit of a relic of older versions of Laravel, but they haven't been removed or even deprecated (AFAIK) so they can still come in handy.

This is a neat alternative to full-blown event handling classes if you just need to keep some basic (read "synchronous") functionality tied to specific events on a model instance.

I even like to take this one step further and move this boot method out into my own base model, each closure calling an empty public method defined in the base class that can easily be overridden in child models.

The docs for event handling have changed quite a bit over the years; I like to keep these "simple" events in my models for convenience, but feel free to register them wherever you like.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.