I have two model (Cart & AcceptedCart) and I want to run this method when a row insrted in AcceptedCart model :
public function dataUpdated()
{
$cart = Cart::where('id' , $this->cart_id)->first();
$sum = 0;
$acceptedCarts = AcceptedCart::where('cart_id' , $this->cart_id)->get();
foreach($acceptedCarts as $acceptedCart){
$sum += $acceptedCart->accepted_count;
}
if ($sum == $cart->product_quantity){
$cart->full_accepted = true;
$cart->save();
}
}
as you see, I change full_accpted = true in the cart model.
the AcceptedCart migration is :
public function up()
{
Schema::create('accepted_carts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('cart_id');
$table->unsignedBigInteger('accepted_by')->nullable();
$table->integer('accepted_count');
$table->timestamps();
$table->foreign('cart_id')->references('id')->on('carts');
});
}
and Cart migration is :
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->id();
$table->boolean('full_accepted')->default(false);
$table->text('address');
$table->timestamps();
});
}
how can I call this dataUpdated method every time a row inserted to AcceptedCart model?
You can use the models
booted()method to achieve this simple task, also you can use the separate observer class to listen to model events like created/updated/deleted, etc.E.g. 1. How you can listen to model events in the same model.
E.g. 2. You can use Observer class to listen to events
You can learn more here about Model Observers