framework
framework copied to clipboard
Eloquent using appends is getting error when eloquent addSelect
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
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.
Thanks a lot