Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Eager Loading Result

i want try to merge a result from eager loading:

Here is my result:

 [{"id":3,"name":"John","email":"[email protected]","username":"johndoe",
 "user_detail":{"address":"anywhere in the world","country":"Somewhere","city":"Somecity","phones":"012-12345","logo":"cute.jpg","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}}]

what i want to achieve is delete the user detail and join all the json become one like this:

 [{"id":3,"name":"John","email":"[email protected]","username":"johndoe","address":"anywhere in the world","country":"Somewhere","city":"Somecity","phones":"012-12345","logo":"cute.jpg","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}]

My model:

/*User Model*/ 
public function user_detail(){
  return $this->hasOne('App\UserDetail');
}

/*User Detail Model*/ 
public function user(){
  return $this->belongsTo('App\User');
}

My Controller:

$user= User::with('user_detail')->where('username', $username)->get();

Is there any function to merge the json become one?.

Thanks

like image 286
ssuhat Avatar asked Dec 02 '25 11:12

ssuhat


1 Answers

What you are looking for is array flattening. You can do it like this

    function flatten(array $array) { 
        $return = array(); 
        array_walk_recursive($array, function($a,$b) use (&$return) { $return[$b] = $a; }); 
        return $return; 
    }

and then call this function something like this(Use proper syntax for calling the function if its in the class)

$user= User::with('user_detail')->where('username', $username)->get();
$result = flatten($user);

This will give you the desired result. Hope this helps!

like image 174
Ymartin Avatar answered Dec 05 '25 01:12

Ymartin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!