0

According to the accepted answer in Using Model Events Listener in Laravel 5, the following code should work normally:

class Question extends Model
{
    public function answers()
    {
        return $this->hasMany(Answer::class);
    }

    // this is a recommended way to declare event handlers
    protected static function boot() {
        parent::boot();

        // before delete() method call this
        static::deleting(function($question) {
            $question->answers()->delete();
        });
    }
}

However, after performing the following actions in php artisan tinker:

$q = App\Question::create()
$q->answers()->create()
$q->delete()

The answer still persists in the database. It seems, that the event handler on Question model does not get triggered. How do I fix this?

Community
  • 1
  • 1
Alex Lomia
  • 6,705
  • 12
  • 53
  • 87

2 Answers2

2

First of all, I would answer with a comment if I could.

Hi, as far as I know the deleting event is only getting fired if you delete each model explicitly.

From answer in Soft Delete Cascading with Laravel 5.2

Community
  • 1
  • 1
maltalk
  • 156
  • 1
  • 7
  • Thanks for the answer. What does explicit deletion mean? – Alex Lomia Apr 17 '16 at 20:27
  • 1
    You must go element by element. Example: `static::deleting(function($question) { foreach ($question->answers()->get() as $answer) { $answer->delete(); } });` – maltalk Apr 17 '16 at 20:36
1

You should add to AppServiceProvider in boot action you code, like this

\App\Questions::deleting(function($answers) {
           $answers = Answers::where('question_id', '=', $answer->id)
                   ->get();
           foreach ($answers as $answer) {
               // and here delete questions
           }

       });
Vahe Galstyan
  • 1,681
  • 1
  • 12
  • 25