Last active
March 28, 2020 21:45
-
-
Save nwaughachukwuma/8620b5138744b53f3fd0a09ebed374ad to your computer and use it in GitHub Desktop.
A post model with it's relationships
This file contains 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 Post extends Model | |
{ | |
public function user() | |
{ | |
return $this->belongsTo('\App\User'); | |
} | |
public function comments() | |
{ | |
return $this->hasMany('\App\Comment'); | |
} | |
// this is a recommended way to declare event handlers | |
public static function boot() { | |
parent::boot(); | |
self::deleting(function($post) { // before delete() method call this | |
$post->comments()->each(function($comment) { | |
$comment->delete(); // <-- direct deletion | |
}); | |
// do the rest of the cleanup... | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment