0

I'm trying to trigger some action after create and update my model following Laravel docs regarding events and observers. So I have:

\App\Observers\PedidoObserver.php:

<?php

namespace App\Observers;

use App\Pedido;
use Illuminate\Support\Facades\Log;
class PedidoObserver {
    public $afterCommit = true;

    public function created(Pedido $pedido)
    {
        Log::info('A new order has been created and the properly method has been triggered');
    }
    public function updated(Pedido $pedido)
    {
        Log::info('An order has been updated and the properly method has been triggered');
    }
}

Boot function in \App\Providers\EventServiceProvider.php:

public function boot(){
    parent::boot();
    Pedido::observe(PedidoObserver::class);
}

Created method succeeds when a new order is created from one of my controllers with this code:

//...
Pedido::create($pedido['header'])->save();

however, even though my order is successfully updated from another controller method, the updated event never gets executed:

//...
Pedido::where([['numserie', $numserie], ['estado', 'SC']])->update(['estado'=> 'P', 'estadonombre' => 'Pendiente de pago'])

1 Answer 1

2

It’s because model events dont fired in batch update models.

You must update EXACTLY model, not with where query.

You need to change your logic for use observers for something like this:

Pedido::where([['numserie', $numserie], ['estado', 'SC']])->firstOrFail()->update(['estado'=> 'P', 'estadonombre' => 'Pendiente de pago'])
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, I understand it. But I don't need firstOrFail because is a massive update.
Than, you cannot use Model Events in your case.
Btw, you can get your models with query and foreach them with update - events will be fired. But it's not the right solution :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.