How to convert an eloquent query into an array - laravel

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)

In this particular case, the lists() function may do what you want.
Auth::User()->usergroup()->lists('group_id')

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').

Related

Laravel - How to extract one field for items in a model to an array?

I have a table that has a one-to-many relationship with another table.
Call them tables parent and child
child has a field called field1
I am trying to get an array of all field1 values.
In the parent Model, I have this function that gets me all children of parent
public function children()
{
return $this->hasMany(Child::class);
}
Now, in the parent model, I also want to get all field1 values.
I can get all the children like so:
$children = $this->children->all();
But I just can't figure out how to then index into this to get all the field1 values.
Maybe it is better to just use $this->children in which case it is a Collection and then use some sort of Collection method to extract field1?
I tried
$this->children->only(['field1'])
but that returned nothing, even though field1 certain exists.
Ideas?
Thanks!
You can use pluck method of collecion to get an array of field1 values:
$parent->child->pluck('field1');
Or better, you can use pluck method of query builder (see section Retrieving A List Of Column Values), being even more efficient, with same result:
$parent->child()->pluck('field1');
map() is the function you are looking.
$children = $this->children->all()->map(function($children) {
return $children->field1;
});
A shorter version using Higher Order Message.
$children = $this->children->all()->map->field1;

after filtering a plucked laravel collection, the indexed array change to Associative array

I have a collection of model eloquent such as user model, i use the pluck method to get the only post_idfrom this collection, this method give me the indexed array of post_id, but when i use filter or unique method for this indexed array the result change to Associative array. i don't want a assoc array in result. I want just the unique of post_id's in the indexed array. laravel auto changing my result.
$this->posts->pluck('post_id')->unique('post_id')
result is :{ "1": 1 , "2": 2 }.
Is this can a bug or I have a mistake in fetching data by methods?
You can use groupBy like this :
$this->posts->groupBy('post_id')->pluck('post_id');

Laravel Eloquent ORM - How to get the all the properties of afrom/of a collection in a array?

$user_emails = ["email_1#domain.com", "email_2#domain.org"];
$users = Users::whereIn("email", $user_emails);
The table for users also has a phone column for each user. What's the best way to get a list/array of the phone number as an array?
$users->all()->phone(); // Like (which is not correct)
Try to use get() like :
$users = Users::whereIn("email", $user_emails)->get(['phone'])->toArray();
Or also pluck() like :
$users = Users::whereIn("email", $user_emails)->pluck('phone')->all();
Hope this helps.
Use pluck method to fetch a specific column's values and then use toArray on returned Collection object to get results as an array.
$phoneNumbers = Users::whereIn("email", $user_emails)->pluck('phone')->toArray();
You can get all column data with get()
Example:
$user = $user::where('email', $user_emails)->get();
You can get the list with foreach loop method.

laravel database query Does `where` always need `first()`?

I am new to laravel and confused about some query methods.
find($id) is useful and returns a nice array, but sometimes I need to select by other fields rather than id.
The Laravel document said I could use where('field', '=', 'value') and return a bunch of data, which is fine.
What I can't understand is why I need to add ->first() every time, even if I am pretty sure there is only one single row matches the query.
It goes like this:
$query->where(..)->orderBy(..)->limit(..) etc.
// you can chain the methods as you like, and finally you need one of:
->get($columns); // returns Eloquent Collection of Models or array of stdObjects
->first($columns); // returns single row (Eloquent Model or stdClass)
->find($id); // returns single row (Eloquent Model or stdClass)
->find($ids); // returns Eloquent Collection
// those are examples, there are many more like firstOrFail, findMany etc, check the api
$columns is an array of fields to retrieve, default array('*')
$id is a single primary key value
$ids is an array of PKs, this works in find method only for Eloquent Builder
// or aggregate functions:
->count()
->avg()
->aggregate()
// just examples here too
So the method depends on what you want to retrieve (array/collection or single object)
Also the return objects depend on the builder you are using (Eloquent Builder or Query Builder):
User::get(); // Eloquent Colleciton
DB::table('users')->get(); // array of stdObjects
even if I am pretty sure there is only one single row matches the query.
Well Laravel cant read your mind - so you need to tell it what you want to do.
You can do either
User::where('field', '=', 'value')->get()
Which will return all objects that match that search. Sometimes it might be one, but sometimes it might be 2 or 3...
If you are sure there is only one (or you only want the first) you can do
User::where('field', '=', 'value')->first()
get() returns an array of objects (multiple rows)
while
first() returns a single object (a row)
You can of course use get() when you know it will return only one row, but you need to keep that in mind when addressing the result:
using get()
$rez = \DB::table('table')->where('sec_id','=','5')->get();
//will return one row in an array with one item, but will be addressed as:
$myfieldvalue = $rez[0]->fieldname;
using first()
$rez = \DB::table('table')->where('sec_id','=','5')->first();
// will also return one row but without the array, so
$myfieldvalue = $rez->fieldname;
So it depends on how you want to access the result of the query: as an object or as an array, and also depends on what "you know" the query will return.
first() is the equivalent of LIMIT 1 at the end of your SELECT statement. Even if your query would return multiple rows, if you use first() it will only return the first row

Laravel - When to use ->get()

I'm confused as to when ->get() in Laravel...
E.G. DB::table('users')->find(1) doesn't need ->get() to retrieve the results, neither does User::find(1)
The laravel docs say "...execute the query using the get or first method..."
I've read the Fluent Query Builder and Eloquent docs but don't understand when the usage of get() is required...
Thanks for the help
Since the find() function will always use the primary key for the table, the need for get() is not necessary. Because you can't narrow your selection down and that's why it will always just try to get that record and return it.
But when you're using the Fluent Query Builder you can nest conditions as such:
$userQuery = DB::table('users');
$userQuery->where('email', '=', 'foo#bar.com');
$userQuery->or_where('email', '=', 'bar#foo.com');
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.
// Done with building the query
$users = $userQuery->get();
For find(n), you retrieve a row based on the primary key which is 'n'.
For first(), you retrieve the first row among all rows that fit the where clauses.
For get(), you retrieve all the rows that fit the where clauses. (Please note that loops are required to access all the rows or you will get some errors).
find returns one row from the database and represent it as a fluent / eloquent object. e.g. SELECT * FROM users WHERE id = 3 is equivalent to DB::table('users')->find(3);
get returns an array of objects. e.g. SELECT * FROM users WHERE created_at > '2014-10-12' is equivalent to DB::table('users')->where('created_at', '>', '2014-10-12')->get() will return an array of objects containing users where the created at field is newer than 4014-10-12.
The get() method will give you all the values from the database that meet your parameters where as first() gets you just the first result. You use find() and findOrFail() when you are searching for a key. This is how I use them:
When I want all data from a table I use the all() method
Model::all();
When I want to find by the primary key:
Model::find(1)->first();
Or
Model::findOrFail(1)->first();
This will work if there is a row with a primary key of one. It should only retrieve one row so I use first() instead of get(). Remember if you deleted the row that used key 1, or don't have data in your table, your find(1) will fail.
When I am looking for specific data as in a where clause:
Model::where('field', '=', 'value')->get();
When I want only the first value of the data in the where clause.
Model::where('field', '=', 'value')->first();
Basically what you need to understand is that get() return a collection(note that one object can be in the collection but it still a collection) why first() returns the first object from the result of the query(that is it returns an object)
#Take_away
Get() return a collection first() return an object
You can use get() method with latest() method to get the latest record that were recently added to your table
For example
$user=Student::latest()->get();
return all the data in descending order

Resources