laravel 5.5 I need to include a variable inside a json type array

2

I need to include $ token within the $ user array where I save my query, I'm using the laravel 5.5 framework

 protected function respondWithToken($token,$documento){
    $user = User::select('id','nombre','email')->where('documento', $documento)->get();

     $token =  [
         'access_token' => $token,
         'token_type' => 'bearer'
     ];


    return $user;

}

I know that I can join and concatenate within an array function but it would stay that way, and it's not the way I look. I want to include it in a single array.

{
    "user": [
        {
            "id": 2,
            "nombre": "Pedro",
            "email": "[email protected]"
        }
    ],
    "token": "sfgt854dfgdf54dfg5df4gdf98g4df",
    "token_type": "bearer"
}

I need to include that variable token inside my object and return a json in this way

[
    {
        "id": 2,
        "nombre": "Pedro",
        "email": "[email protected]",
        "token": "sdjkfhsdk65468541sdf3"

    }
]
    
asked by Joel Sanchez 09.05.2018 в 21:39
source

3 answers

2

Hello for that kind of cases it's good to use compact

protected function respondWithToken($token,$documento){
    $user = User::select('id','nombre','email')->where('documento', $documento)->get();
    $token_type = 'bearer';
    $conjunto_variables = compact('user','token','token_type ');

    return $conjunto_variables ;

}
  

What does compact ?

Good compact in simple terms creates an array with variables and their values, it is very useful if you want to send many variables at the same time and be able to call them in the view or where you return them.

Its operation is mainly based on the fact that the name of the variable remains as a key to call it. Example: in your compact I made that user is the name of your variable, well with the same name you can call it in another part like $user , since I returned it in that compact and the same thing I can do with the rest of the variables.

  

PS: for the compact to work it has to be in quotes and   have on behalf of the variable no other. I hope it serves you. Greetings!.

    
answered by 09.05.2018 в 22:48
0
    $user = User::select('id','nombre','email')->where('documento', $documento)->first()->toArray(); 
//first en vez de get

     $token =  [
         'access_token' => $token,
         'token_type' => 'bearer'
     ];


    return json_encode($user + $token);

Thanks to adolfo abegg hahaha

    
answered by 10.05.2018 в 14:04
0

It seems to me that the simplest thing is to add the index you want to the $ user array:

$user['token'] = $token['access_token']

In the case that $ user is an array, you can always access the first element (I understand that even if it is an array you are only looking for a user) and do the same:

$user[0]['token'] = $token['access_token']
    
answered by 10.05.2018 в 14:29