Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel observer not working on bulk insert

I have to save data in bulk.Data is saving but observer not working. I tried all methods of an observer (created, creating, saving, saved) but no response.

foreach( $departments as $department) {
         $data[] = [
             'department_id' => $department,
             'name'          => $name,
             'description'   => $description,
         ];
}

if(count($data) > 0) {
   JobDescription::insert($data);
}

namespace App\Observers;
use Auth;

class JobDescriptionObserver
{
    public function created($model)
    {
        echo 'created';
        die;
     }
}
like image 984
Ameer Avatar asked Feb 26 '19 05:02

Ameer


1 Answers

This behavior is expected and documented in a bright red warning:

When issuing a mass update via Eloquent, the saved and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.

https://laravel.com/docs/5.7/eloquent#events

If you require events to be dispatched when models are created, then you must save them one by one instead:

foreach($departments as $department) {
        Jobdescription::create([
             'department_id' => $department,
             'name'          => $name,
             'description'   => $description,
         ]);
}

The reason mass inserts and updates behave differently is because the underlying SQL query for a mass insert/update is different than the query for updating a single row. Mass updates don't allow Eloquent to retrieve a list of IDs from the query result, which means it doesn't know which models were updated and therefore can't dispatch an event for each one. Single-row updates, on the other hand, allow Eloquent to get the lastInsertId from the query result.

like image 177
Travis Britz Avatar answered Nov 11 '22 15:11

Travis Britz