Skip to content

Instantly share code, notes, and snippets.

@nwaughachukwuma
Last active March 28, 2020 21:41
Show Gist options
  • Save nwaughachukwuma/8028061ae45393ed4382086ec29982bb to your computer and use it in GitHub Desktop.
Save nwaughachukwuma/8028061ae45393ed4382086ec29982bb to your computer and use it in GitHub Desktop.
A user model with it's relationships
<?
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function photos()
{
return $this->hasMany('\App\Photo');
}
public function posts()
{
return $this->hasMany('\App\Post');
}
// this is the recommended way for declaring event handlers
public static function boot() {
parent::boot();
self::deleting(function($user) { // before delete() method call this
$user->photos()->each(function($photo) {
$photo->delete(); // <-- direct deletion
});
$user->posts()->each(function($post) {
$post->delete(); // <-- raise another deleting event on Post to delete comments
});
// do the rest of the cleanup...
});
}
}
@matiaslauriti
Copy link

Could you add <? at the beginning so the code gets colored ?

@nwaughachukwuma
Copy link
Author

Ok I will, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment