0
votes

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

2
Are you looking for toArray() ?Niklesh Raut

2 Answers

1
votes

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.

0
votes

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]);