framework icon indicating copy to clipboard operation
framework copied to clipboard

Eloquent using appends is getting error when eloquent addSelect

Open barisbora opened this issue 11 years ago • 2 comments

when add extra logic column in eloquent so its depend on another column, its causes error when addSelect

protected $appends = ['is_admin'];

public function getIsAdminAttribute()
{
      if ( $this->attributes['user_type'] == 'A' ) return true;
      return false;
}

Post and User model related, In Post model

public function User ()
{
      return $this->hasOne( 'App\User' );
}

when call eloquent

\App\Post::with([
    'User' => function($q) {
         $q->addSelect('id', 'username');
    }
])->addSelect('id', 'user_id', 'title', 'description')->get();

its getting error ( Undefined index: user_type ) , when i add user_type column in $q->addSelect('id', 'username', 'user_type'); subquery its work perfectly and return this columns in User

'id', 'username', 'user_type', is_admin

barisbora avatar Jun 02 '15 12:06 barisbora

This is the expected behavior. Before calling addSelect(), nothing is selected. After you call it, only id and username is fetched and not user_type. So obviously it doesn't exist in the attributes array and you get that error.

lukasgeiter avatar Jun 02 '15 13:06 lukasgeiter

Thanks a lot

barisbora avatar Jun 02 '15 13:06 barisbora