Skip to content
Advertisement

Laravel, how to ignore an accessor

I have a model with a custom accessor so I get that custom attribute,

    class Order extends GSModel{

        $appends = ['orderContents'];

        public function getOrderContentsAttribute()
        {
            return $this->contents()->get();
        } 
 }

But now, in one case, I need to get only some fields, without this OrderContents one.

$openOrders         = Order::open()->has('contents')->get(['id','date','tableName']);

But doing it this way, it returns me the OrderContents as well.. is there a way to not get that field?

Thanks!

Advertisement

Answer

There’s no way to do it in one go, so here’s what you need:

$openOrders = Order::open()->has('contents')->get(['id','date','tableName']);

$openOrders->each(function ($order) {
  $order->setAppends([]);
});

Alternatively, you may use Laravel’s Higher Order Messaging on the last step:

$openOrders->each->setAppends([]);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement