Merge two eloquent collections into one object property?

1.1k Views Asked by At

We can create empty objects in php using th stdClass and we can add properties to it like this:

$data = new stdClass;

$data->xyz = something;

But how could we add more things to a property? i mean something like this:

$data->xyz += somethingElse;

Is that possible?

What i want to do is this: i have to get some data from a database and i would like to store records of two tables in one property. To get data from a table and store it in a property i do this:

    $data = new stdClass;

    $data->gallery = \DB::table('RestaurantMenuOptions')
        ->select('Name', 'Image')
        ->get();

    $data->gallery2 = \DB::table('Promotions')
        ->select('Name', 'Image')
        ->get();

What i would like is to store them all in a single gallery property. By the way i use Laravel 5.

Edit 1

What i want is to join the data called from the table 'RestaurantMenuOptions' and 'Promotions' into one property of $data. I'm guessing if its possible to join two variables or if it's possible to get data from two unrelated tables using Eloquent?

What i've thought so far is to convert the models to array and then join them, but how do i convert the joined arrays to a model so that it in the views?

Edit 2

I found that it's possible to merge eloquent collections, but if the tables has the same type of PK and there are repeated records with same PK, they'll be overridden, so i decided to convert the collections to arrays merge them and access to them like them like this:

{{ $item['key'] }}

If someone has a better way to do it i'll apreciate it.

1

There are 1 best solutions below

5
On

I think that a better way would be doing a for loop instead to make it somewhat more dynamic.

Code:

class Data {
    private $property, $property2;

    public function  __construct($property,$property2) {
        $this->Property = $property;
        $this->Property2 = $property2;
    }
}

$dataArray = array();

$dataArray[] = new Data('Name',Image);
$dataArray[] = new Data('Name',Image);

print "<pre>";
print_r($dataArray);
print "</pre>";

for ($i=0; $i < count($dataArray); $i++) { 
    // do something with the array of objects
}