Reputation: 2963
I have the following eloquent query which uses a many-to-many relationship to grab all groups associated with the authenticated user.
$usergr = Auth::User()->usergroup()->get();
Pivot table
ID|user_id|group_id
1 |1 |2
2 |1 |3
I would like to convert this to an array of group_id
. So fare it is a collection object however I need this converted to an array to be used on another query.
I have this so far:
foreach ($usergr as $obj)
{
$array[]= (array) $obj;
}
The query I for teh array is below:
$usergrsub = DB::table('group_subjectlist')->whereIn('group_id', $array)
->select('subjectlist_id')
->distinct()->get();
However the query above is not recognising the $array
variable
(I use version 4.2)
Upvotes: 0
Views: 2408
Reputation: 1035
Most result objects returned by Laravel's builders have a toArray()
method that will convert the object into an array.
The whereIn
method expects an array of values, but the result of get()
will be a collection of objects, which if converted to an array will be an array of associative arrays.
If you need the get()
result only for the whereIn
query you should use lists('group_id')
instead of get()
. Otherwise consider using pluck('group_id')
.
Upvotes: 1