Last active
March 28, 2020 21:41
-
-
Save nwaughachukwuma/8028061ae45393ed4382086ec29982bb to your computer and use it in GitHub Desktop.
A user model with it's relationships
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
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... | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ok I will, thanks