Jordi Puigdellívol Jordi Puigdellívol - 6 months ago 96
PHP Question

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!

Answer

Okay I'm not saying this is a good solution, but it works and you get around using a loop...

Add this to your model:

public static $withoutAppends = false;

protected function getArrayableAppends()
{
    if(self::$withoutAppends){
        return [];
    }
    return parent::getArrayableAppends();
}

Then when you want to disable the $appends properties:

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