laravelmutators

laravel how to call a method when a row inserted in model?


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?


Solution

  • 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.

    class AcceptedCart extends Model
    {
        /**
         * The "booted" method of the model.
         *
         * @return void
         */
        protected static function booted()
        {
            static::created(function ($acceptedCart) {
               $acceptedCart->dataUpdated();
            });
            // Similarly you can do for updated/deleted events as well
        }
    }
    

    E.g. 2. You can use Observer class to listen to events

    <?php
     
    namespace App\Observers;
     
    use App\Models\AcceptedCart;
     
    class AcceptedCartObserver
    {
        /**
         * Handle the AcceptedCart "created" event.
         *
         * @param  \App\Models\AcceptedCart  $acceptedCart
         * @return void
         */
        public function created(AcceptedCart $acceptedCart)
        {
            $acceptedCart->dataUpdated();
        }
     
        /**
         * Handle the AcceptedCart "updated" event.
         *
         * @param  \App\Models\AcceptedCart  $acceptedCart
         * @return void
         */
        public function updated(AcceptedCart $acceptedCart)
        {
            // Similarly for update
        }
    }
    

    You can learn more here about Model Observers