Search code examples
phpjsonlaravellaravel-5

Merge Eager Loading Result


i want try to merge a result from eager loading:

Here is my result:

 [{"id":3,"name":"John","email":"john@doe.com","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":"john@doe.com","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


Solution

  • 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!