vendredi 10 janvier 2020

laravel one to one relation return as one object

I have a One to One relation. I would like to return json data, in which one to one ralation model show like one object, not as child.

class User extends Model
{
    protected $fillable = ['email'];

    public function profile() {
        return $this->hasOne(Profile::class);
    }
}

class Profile extends Model
{
    protected $fillable = ['first_name', 'last_name'];
}

I want to retun json in controller, like:

[
   {
      email: "test@test.test",
      first_name: "Teszt",
      last_name: "Jhon"
   },
   {
      email: "test2@test2.test",
      first_name: "Teszt2",
      last_name: "Jhon2"
   }
]

But if I do this:

return User::with('profile')->get();

Only get this:

[
   {
      email: "test@test.test",
      profile: {
         first_name: "Teszt",
         last_name: "Jhon"
      }
   },
   {
      email: "test2@test2.test",
      profile: {
         first_name: "Teszt2",
         last_name: "Jhon2"
      }
   }
]

What is the best solution to get the first json variation?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire