skip to Main Content

Is it possible to have eager loading without $append attributes? I have following code:

Product model:

public function category(): BelongsTo
    {
        return $this
            ->belongsTo(ProductCategory::class, 'product_category_id');
    }

public static function adminTableData(): Builder
    {
        return self::query()->select('*')
            ->with(['category' => function($query)
            {
                return $query->select('id', 'name');
            }]);
    }

Company model:

protected $appends = [
        'admin_table_logo',
        'edit',
        'remove',
    ];

2

Answers


  1. Yes you can. Like this. I commented inline:

    namespace AppModels;
     
    use IlluminateDatabaseEloquentCastsAttribute;
    use IlluminateDatabaseEloquentModel;
     
    class User extends Model
    {
    
        protected $appends = ['appendSomeAttributesToUser'];
    
        /**
         * Determine if the user is an administrator.
         */
        protected function appendSomeAttributesToUser($user): ?Attribute
        {
            // You have to check the condition. Maybe if user is a admin!
            return $user->isAdmin ? [
              'admin_table_logo',
              'edit',
              'remove',
            ] : null;
        }
    }
    
    Login or Signup to reply.
  2. You can try this.

    public static function withoutAppends(): Builder
    {
        $model = (new static);
        $model->setAppends([]);
    
        return $model->newQuery();
    }
    

    Modify adminTableData function

    public static function adminTableData(): Builder
    {
        return self::withoutAppends()->select('*')
            ->with(['category' => function($query)
            {
                return $query->select('id', 'name');
            }]);
    }
    

    The answer is based on how to ignore accessor

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search