'Laravel Illuminate\Database\Eloquent\Collection
I normally select my items seperatly with Eloquent Laravel
$b = Booking::where("id","=",$id)->get();
What I get is an Illuminate\Database\Eloquent\Collection with one item. I put them in an array later on so that I have an array of these Illuminate\Database\Eloquent\Collection objects.
However sometimes I need more of them, so I do something like that:
$bs = Booking::where("date","=",$today)->get();
Now this is a collection with multiple items. Is there an easy way to change a Illuminate\Database\Eloquent\Collection of several items in a array of Illuminate\Database\Eloquent\Collection with single items?
Sure I can do this:
$bs = Booking::where("date","=",$today)->get();
foreach ($bs as $i=>$b) $bs2[] = Booking::where("id","=",$b->id)->get();
But selecting again from DB seems to be a quite stupid solution.
EDIT:
If I do this I have:
- $bs as a 'Collection'-object holding 15 'Booking'-objects inside.
- $bs1 as an Array holding 15 'Collection'-objects with each holding 1 'Booking'-object inside. (that's what I want to have)
->toArray() creates an Array holding 15 Arrays. That's not what I want to have - I need the objects. As the eloquent provides features like a date field is automatically a DateTime object
Solution 1:[1]
Use toArray() function and you are ready to go,
$bs = Booking::where("date","=",$today)->get()->toArray();
Now you will have array of data returned from DB.
Solution 2:[2]
You can do this:
$bs = Booking::where("date","=",$today)->get();
foreach ($bs as $i=>$b) {
$bs2[] = collect([$b]);
}
This gives you an array of Illuminate\Support\Collection collections with one item each.
If you need Illuminate\Database\Eloquent\Collection collections:
$bs2[] = new \Illuminate\Database\Eloquent\Collection([$b]);
Solution 3:[3]
Try the following.
$bs = Booking::where("date", "=", $today)->get();
$new_bs = $bs->toArray();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Faraz Irfan |
| Solution 2 | Jonas Staudenmeir |
| Solution 3 | Karl Hill |
