dacastro4's avatar

Laravel, trying to ignore $appends

I'm trying to ignore all my $appends in my User model just for one time. I need all those every time on my app but this one time I don't need it and it's slowing down the performance of my query. If any can helping I'll totally happy!

0 likes
9 replies
jlrdw's avatar

Normally some code is shown so someone can help.

dacastro4's avatar

Hey @jlrdw, I just a model

class User extends Authenticatable
{
    use SoftDeletes;


    public $appends = [
        'full_name',
        'name',
        'since',
        'new_customer',
        'th_roles'
    ];
}

And i'm trying to remove all of those $appends from my eloquent query.

1 like
crnkovic's avatar

I believe there is a method setHidden(array $attributes) or just makeHidden(array $attributes) that makes a attributes hidden just for one query.

"Likewise, if you would like to make some typically visible attributes hidden on a given model instance, you may use the makeHidden method." - docs

1 like
dacastro4's avatar

@lars6 the solution it's pretty much what @jcrnkovic said the problem is that if you have a collection, you need to loop through and call the method because only works in "a given model instance".

The correct method is makeHidden(array $attributes).

Docs: Laravel Eloquent Docs

1 like
Lars-Janssen's avatar

@dacastro4 thanks. I've made a trait:

trait CustomModelLogic
{
    /**
     * @var bool
     */
    public static $withoutAppends = false;

    /**
     * Check if $withoutAppends is enabled.
     *
     * @return array
     */
    protected function getArrayableAppends()
    {
        if(self::$withoutAppends){
            return [];
        }
        return parent::getArrayableAppends();
    }
}
2 likes
Reppair's avatar

When I do not need the model to utilize the $appends attribute I just set it as an empty array on the fly like so:

$model->appends = [];
$model->toJson(); 
gr_nunari's avatar

use this one in your particular method. Model::$withoutAppends = true;

Please or to participate in this conversation.