Home > Software design >  Laravel observer taking too long when updating
Laravel observer taking too long when updating

Time:11-13

How to use Laravel observer to update specific fields.

ItemController.php

public function update(ItemRequest $request, Item $item)
{
    abort_if(Gate::denies('item-update'), Response::HTTP_FORBIDDEN, '403 Forbidden');
    
    $item->update($request->all());

    if ($request->has('tags')) {
        $item->tags()->attach($request->tags);
    }

    $item = new ItemResource($item);

    return $this->sendResponse(Response::HTTP_OK, $item, 'Record has been updated successfully.');
}

ItemObserver.php

public function updated(Item $item)
{
    $item->update([
        'price_total' => $item->quantity * $item->price,
    ]);
}

The above technique resulted in an endless loop. Should I update the price_total field from the controller?

CodePudding user response:

You make a update command in observer updated, it will make a loop. Just dont use $item->update , only :

 $item->price_total = $item->quantity * $item->price

CodePudding user response:

Try this

$item->price_total = $item->quantity * $item->price;
$item->saveQuietly();

in observer

  • Related