jeudi 12 octobre 2017

Eloquent Relationship Update through an Observer not working

Let us assume that we have an Order model that captures details about a Customer's order. To keep track of the orders in terms of which customer they belong to we create a customer_orders table.

namespace TroubledMind\NeedsHelp
{
  //imports

  class AdviceOrder extends Model
  {
    protected $fillable = [...];
  }

  class FrustratedCustomer extends Model
  {
    //properties
  }

  class FrustratedCustomerOrder extends Model{}
}

Assuming I have created an observer class ~ AdviceOrderObserver that should respond to created event in the model I am unable to have my FrustratedCustomerOrder table with the id of the AdviceOrderandFrustratedCustomer` respectively.

Supposedly the code snippet below works:

namespace UnObserving\Observers
{
  class UncooperativeOrderObserver
  {
    public function created(AdviceOrder $order)
    {
       $customer = Customer::where('number', $order->id)->get();

       if($customer->isNotEmpty()){
          FrustratedCustomerOrder::updateOrCreate(
             array('advice_order_id' => $order->id),
             array(
               'advice_order_id' => $order->id,
               'frustrated_customer_id' => $customer->id,
             )
           );
       }
   }
 }

I can only dd the observer parameter whic in this case is $oder and as for everything else nothing happens. What am I doing wrong? Am I using the obserber implementation incorrectly? I have added the line below on my AppServiceProvider:

Order::observe(UncooperativeOrderObserver::class);

Anyone with an idea of how I can use the Observer implementation to update my pivot table?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire