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;
}
}
This behavior is expected and documented in a bright red warning:
When issuing a mass update via Eloquent, the
saved
andupdated
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With