Result of a successful download of the Merge Eager

I want to try to combine the result with the 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 remove the user detail and join everything like the json becomes:

 [{"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 some json merge function that becomes one ?.

thank

+3


source to share


1 answer


What you are looking for is array alignment. 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 correct syntax to call the function if it is in a class)



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

      

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

+3


source







All Articles