Murlidhar Fichadia
Murlidhar Fichadia

Reputation: 2609

Get Array / List of data for a given field and Use it in Eloquent Query - Laravel

I am trying to Get list of results from a particular table and a particular column.

Works

$curr_user_offering = Offering::where('user_id', Auth::user()->id)->first()->language; 

Returns

Spanish

Fails

$curr_user_offering = Offering::where('user_id', Auth::user()->id)->get()->language; 

Error

I tried

$result = $curr_user_offering->toArray();
return $result;

Exception in Collection.php line 1479:
Property [language] does not exist on this collection instance.

but language do exist.

I want to return

['English','Spanish','French']

Finally, I want to use this to loop through a query with a check if other user have profile quite the opposite. That is, If user_1 is offering : English and user_2 wanting : English. I should return a true result of that user profile.

The query below works just fine: it checks if a user is not the one loggedin meaning other users who would like to study X language which current loggedin User is Offering.

$match = Wanting::where([['id', '<>', Auth::user()->id],['language',$curr_user_offering]])->get();

But I need a way to loop though loggedin User Wanting languages and loop through each user and find which ones can offer that.

Upvotes: 1

Views: 1886

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

The following code doesn't work, because get() returns a collection of models, not a single model:

Offering::where('user_id', Auth::user()->id)->get()->language;

If you want to get a list of values from a single column, the following should do the trick:

$languages = Offering::where('user_id', Auth::user()->id)->get()->pluck('language')->toArray();

As for the second part of the question, I'm not sure I follow. Getting users that want particular language (Wanting model) works for you, why can't you do the same thing for Offering model?

Upvotes: 2

Related Questions