Is that possible to run this job UpdateRateZone
globally wheneven Consignment
Model gets updated anywhere in the system?
One method is to use Observer
but observer doesn't work when update multiple reccord at once like
Consignment::where('status',1)->update(['address'=>'This']);
Is there anything else we can do?
CodePudding user response:
Yes you can create a Event Listener for your model. You can read up on more info here
In short first you need to create an Event for the needed model, so if its a Updated event create something like this.
php artisan make:event Consignment/Updated
In that file add
class Updated
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* @var Consignment
*/
public $consignment;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Consignment $consignment)
{
$this->consignment= $consignment;
}
/**
* Get the event consignment property
*
* @return Consignment
*/
public function getConsignment()
{
return $this->consignment;
}
}
Now you must create a Listener for this event
php artisan make:listener Consignment/UpdatedEvent
And in the handle function add youre logic
/**
* Handle the event.
*
* @param Updated $event
* @return void
*/
public function handle(Updated $event)
{
//
}
And all that is left after that is to register the events for you Model and you do that in your Consignment.php class where you add
/**
* The event map for the category.
*
* @var array
*/
protected $dispatchesEvents = [
'updated' => Updated::class,
];
CodePudding user response:
As per laravel docs :
When issuing a mass update via Eloquent, the saving, saved, updating, 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.
Laravel does not fire updated
event in case of mass update, so its not possible as per my knowledge. Other way is to do manually.
Other than observers
there is methods such using closures for events and Registering events manually but all these methods would work if only laravel
trigger an event on mass updation
.
CodePudding user response:
When you do this:
Model::where('status',1)->update([some stuff]);
Query Builder's update() method is executed instead of Eloquent's update() method.
If you want to trigger Eloquent events, you need to update rows one by one. You can fire these events manually, but it's tricky and it's a bad idea.
You could just run the UpdateRateZone
job manually for all the Consignments that were updated