Home > Mobile >  Beauty name instead id
Beauty name instead id

Time:07-14

I have a two table:

Users:
id,
name,
role_id

Roles:
id,
name

And i will response to requset like this: user_id, user_name, role_name (not the role_id)

My controller for route function:

public function getUserList(): JsonResponse {
     $users = User::All()->toArray();

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

How include roles.name field in the response ?

CodePudding user response:

Create a relationship on your User model.

class User extends Authenticable
{
    public function role()
    {
        return $this->belongsTo(Role::class);
    }
}

Include the relationship using with().

$users = User::with('role')->get();

This will transform it into the following structure, when the models are transformed to JSON.

[
    {
        "name": "Martin",
        "email": "[email protected]",
        "role": {
            "name": "admin"
        }
    }
]

Working with Laravel, i will call it an anti pattern, transforming objects or data structures to arrays. In between classes, keep em objects for flexibility. In controllers Laravel, is smart enough to automatically transform your data. So the following code, is enough for a JSON route.

public function getUserList()
{
    return User::with('role')->get();
}

CodePudding user response:

public function getUserList(): JsonResponse {
  return response()->json(User::with('role')->get());
}

Note: You don't need to call ->toArray() when returning as a JSON response; that is done automatically

https://laravel.com/docs/9.x/eloquent-relationships#eager-loading

Then user.role.name on your front-end.

If you want user.role_name instead of user.role.name, then you'll need to define an accessor and append it:

User.php:

class User extends Model {
  public $appends = ['role_name'];

  public function role() {
    return $this->belongsTo(Role::class);
  }

  public function getRoleNameAttribute() { 
    return $this->role->name;
  }
}

Now, user.role_name will be available.

  • Related