how to get collection results as array with ids - php

it should be simple but I am missing something,
lets say this simple eloquent:
Post::select('id')->take(5)->get();
I want to get simple array with the results id's so it will look like this:
[1,2,3,4,5]
but i am getting something like this:
[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"}]
flatten() not working and I am getting the same results:
Post::select('id')->take(5)->get()->flatten();
http://laravel.com/docs/master/collections#method-flatten
The flatten
method flattens a multi-dimensional collection into a single
dimension:
what i am missing? I remember there is a short line laravel way of getting this results without iterate through the array and create a new one

just got it, its the lists() that do the magic so the answer is:
Post::select('id')->take(5)->lists('id');
Update:
as of laravel 5.2 lists() become deprecated
The lists method on the Collection, query builder and Eloquent query
builder objects has been renamed to pluck. The method signature
remains the same.
the new method name is pluck which work the same:
Post::select('id')->take(5)->pluck('id');

Related

Laravel: Get model attributes by key array

I'm attempting to access a models attributes by an array of keys. The desired functionality would work something like $model->getAttribute('name'), but accept an array instead of a string.
Let's say we had a model with attributes name of 'A', age of 2 and blood_type of 'B'.
$attributesToPull = ['name', 'age'];
$model->getAttributes($attributesToPull);
// returns ['A', 2]
I've checked through the Laravel docs and cant find anything that quite fits.
The results dont need to come straight from the model, they can be pulled into their own associative array using $model->getAttributes() and then have a native PHP array function such as array_intersect to filter the results, but even then I can't seem to find a function that will allow me to filter an associative array with an indexed array.
Does anyone know how I could go about this, ideally without using a loop or a callback? The answer can be pretty open, it can return a collection or an array and use either the associative array of the model attributes or call a function on the model itself.
The Model has a only method:
$model->only($attributesToPull);

Removing rows from a collection changing types of the collection

I have a two collections. First one is a big collection. Another one is remove list. For example:
$data= List::where('status', true)->get();
$list= List::where('begin_at', '<', Carbon::now())->pluck('id');
$result = $data->whereNotIn('id', $list);
This is just a simple example. I have a dynamic data. My question is:
When i return $data, it returns [{}, {}, ...] format
But when i return $result, it returns {}, {}, ...
I tried to $result->toArray(), $result->toCollapse() but none of them is worked.
Why after the get(), using where condition changing the type of the collection? Why array symbols gone? What is the best practices in here to solution? Thanks in advance.
Use all() on the collection to get it as an array with the Eloquent models intact. If you use toArray() instead, it will convert everything to an plain PHP array.
$data->whereNotIn('id', $list)->all();
See docs here
Calling get() on a model will create a collection, and the collection upon creation will call all() on itself. So after modifying the collection you will need to call all() yourself to the the same "format" as from get().

Difference between get() and first() method in laravel [duplicate]

What is the difference between these methods:
find()
findOrFail()
first()
firstOrFail()
get()
list()
toArray()
I've been using them and each one gives a different result and sometimes I need to add toArray() at the end of get() because my function is expecting an array. Won't the other methods produce arrays as well?
find($id) takes an id and returns a single model. If no matching model exist, it returns null.
findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.
first() returns the first record found in the database. If no matching model exist, it returns null.
firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.
get() returns a collection of models matching the query.
pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.
toArray() converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all() method.
1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
Probably things changed but the findorFail method can take 2 arguments: $id and $columns mixed/array params respectively. Passing a second arg is not required. That said, this would work:
$post = Post::findOrFail([1,2], ['title', 'subtitle']);
If one of the $ids fails, the ModelNotFoundException with message 'No query results for model ... ' will be thrown.

Append a Laravel collection with another collection

I am trying to append an Eloquent collection with another Eloquent collection in Laravel 5.3.
This is what I've done so far:
$entries = Entry::all();
$posts = Post::all();
$entries->merge($posts);
I tried to use merge() as shown in the code above, but it seems that I'm stuck with this kind of problem (since some of them have the same id with the same value):
Collection merge eating up some rows
Any ideas?
For versions < 5.4 you can merge the two eloquent collections by resetting keys with toBase like this:
$mergedCollection = $entries->toBase()->merge($posts);
For versions >= 5.4 you can use concat as suggested by Jason.
I believe you may be looking for concat(). This will append one container to the end of another container, regardless of the keys of either.
$mergedCollection = $entries->concat($posts);
Here's the link: laravel7.X
$collection = collect(['Desk', 'Chair']);
$merged = $collection->merge(['Bookcase', 'Door']);
$merged->all();
if you need to merge big_products and small_products:
$products = $bigProducts->values()->merge($smallProducts->values());
The merge method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection.
But
If the given items's keys are numeric, the values will be appended to the end of the collection:
Thus, all you need is to get rid of keys and you can do it with ->values() function.
Tested on Laravel-6
The merge() method receives an array, so you have to do something like
$entries->merge($posts->toArray());
Laravel Collections: merge() method

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

What is the difference between these methods:
find()
findOrFail()
first()
firstOrFail()
get()
list()
toArray()
I've been using them and each one gives a different result and sometimes I need to add toArray() at the end of get() because my function is expecting an array. Won't the other methods produce arrays as well?
find($id) takes an id and returns a single model. If no matching model exist, it returns null.
findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.
first() returns the first record found in the database. If no matching model exist, it returns null.
firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.
get() returns a collection of models matching the query.
pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.
toArray() converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all() method.
1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
Probably things changed but the findorFail method can take 2 arguments: $id and $columns mixed/array params respectively. Passing a second arg is not required. That said, this would work:
$post = Post::findOrFail([1,2], ['title', 'subtitle']);
If one of the $ids fails, the ModelNotFoundException with message 'No query results for model ... ' will be thrown.

Categories