1
votes

I'm trying to get selected columns instead of full columns.

$profiles= auth()->user()->profile()->where('id', $id)->select('profile.id','profile.name');

and my profile() method

public function profile()
{
    return $this->hasMany(Profile::class)->get();
}

if i remove the ->select('profile.id','profile.name'), it returns full columns of profile table but i just want only a few columns of it. And if I add in ->select() it gives me error of:

BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::select does not exist. in file

Please advise to change the method call. Thank you.

2
There is no such method available for collection helper laravel.com/docs/8.x/collectionsM Khalid Junaid
This is the reason you don't put ->get() after hasMany() in your relationship function; you completely remove the ability to chain queries, like select(), where(), etc, since you're immediately executing the query. Double check the documentation, laravel.com/docs/8.x/eloquent-relationships, none of the example functions use ->get() or ->first() after hasOne(), hasMany(), belongsTo(), etc, and now you know why :)Tim Lewis

2 Answers

2
votes

get() is called before select()(in profile()) which is wrong since then you are trying to call select() method on fetched Collection. So remove get() from your relationship functions.

public function profile()
{
    return $this->hasMany(Profile::class);
}

Note: Do same for user() if you use get() in it.

0
votes

Can you try by changing ->select('profile.id','profile.name') by ->pluck('profile.id','profile.name') ?