How to get a specific field value from a with() in laravel 9

Viewed 21

I have an API in which I want to add some specific values to JWT, the data comes from a table tbl_user which is connected to a different table tbl_user_details, via foreign key user_id. I have a relation between them using belongsTo and hasMany. The tbl_user_details contains a field first_name, which I want to get as a data for a variable $first_name. so that I can add it to JWT.

User Model

public function details()
{
    return $this->hasMany(UserDetails::class, 'user_id', 'user_id');
}

UserDetails Model

public function belongs_to_user()
{
    return $this->belongsTo(User::class, 'user_id', 'user_id');
}

On calling the below controller,

Controller

$first_variable = User::where('user_id', $user_id)->with(['details' => function ($query) {
      $query->select('first_name', 'user_id');
}])
->get();

return response()->json([
      'first_out' => $first_variable,
]);

I get the json output on postman as below,

Postman output

"first_out": [
    {
      "user_id": 1,
      "email": "il.comn@gmail.c",
      "mobile": "RN91919191",
      "role_id": 1,
      "user_status": "active",
      "created_date": "2020-07-29T18:30:00.000000Z",
      "updated_date": "2020-07-29T18:30:00.000000Z",
      "details": [
        {
          "first_name": "Test_User",
          "user_id": 1
        }
      ]
    }

But I only want the output as below

Expected output

"first_out": "Test_User"

What should I do, Please help.

Thanks in advance.

0 Answers
Related