DarkCode999
DarkCode999

Reputation: 182

How to Merge or Combine return data from model in Controller Laravel

I have 3 function, it is a() b() and c()

and then, function a() returned :

{
    id    =>
    total1 =>
}

function b() returned like funcion a() too, but have a different value (total1 and total2)

function c() returned :

{
    id   => //same value just like function a or b
    name =>
}

 

$a = $model->a(); // from function a();
$b = $model->b(); // from function b();
$c = $model->c(); // from function c();

i want combine that 3 returned values into array like this :

array = ['id','name', 'total1', 'total2']

any idea ? Thanks

Upvotes: 1

Views: 1257

Answers (2)

Rahman Qaiser
Rahman Qaiser

Reputation: 672

You can cast the results to array

$a = $model->a()->toArray(); // from function a();
$b = $model->b()->toArray(); // from function b();
$c = $model->c()->toArray(); // from function c();

and then

$data= array_merge($a , $b, $c)

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163838

You can use array_merge() and array_keys():

array_keys(array_merge($a, $b, $c));

If variables are not arrays, convert them to arrays with toArray() or json_decode() first.

If functions return Laravel collections, you can use merge() and keys() helpers.

Upvotes: 1

Related Questions