lundi 5 décembre 2016

Laravel Eloquent relationship data hidden in response

I have two models: User and Group. A user can be a member of just one group, and a group can have multiple users:

User:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'user';
    protected $primaryKey = 'user_id';

    protected $fillable = [];
    protected $visible = ['user_id', 'name', 'points', 'group_id', 'profile'];


    /**
     * Get group where user belongs to
     */
    public function group()
    {
        return $this->belongsTo('App\Models\Group', 'group_id', 'group_id');
    }
}

Group:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Group extends Model
{
    protected $table = 'group';
    protected $primaryKey = 'group_id';

    protected $fillable = [];
    protected $visible = ['group_id', 'name', 'profile'];

    /**
     * Get all group users.
     */
    public function users()
    {
        return $this->hasMany('App\Models\User', 'group_id', 'group_id');
    }
}

Now in my controller, I want to retrieve the user data and the users' group data. Therefore I use this:

$users = User::with('group')
        ->orderBy('points', 'DESC')
        ->take(50)
        ->get();

return response()->json($users);

So far so good. I expect the above to return something like this:

[
  {
    "user_id": 27,
    "name": "linnie15",
    "points": 18565,
    "group_id": 6,
    "profile": null,
    "group": {
      "group_id": 6,
      "name": "White Wall",
      "profile": "Et tempore voluptatibus sunt ratione ut. Eum sint mollitia omnis eius ut facilis aut. Sed quisquam quis velit qui sint soluta. Autem quia ipsam esse sapiente delectus vel."
    }
  },
]

But, here is the problem. The only thing it returns is this:

[
  {
    "user_id": 27,
    "name": "linnie15",
    "points": 18565,
    "group_id": 6,
    "profile": null
  },
]

How is that possible? In fact, I found the solution, by adding 'group' to the $visible array in the User model. But why is that? I mean, should I really add all my relationships to the $visible array? Why would that be necessary. If you query a relationship, you always want the result, isn't it?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2h6zBh5
via IFTTT

Aucun commentaire:

Enregistrer un commentaire