Dran Dev
Dran Dev

Reputation: 519

Laravel - Get returned data from an API within the Controller

I have an API /getuser which returns a reponse along with the user object:

$user = session()->get('current_user');
return response()->json(['user'=>$user]);

Now, I want to get the said returned api within my function public function show_user().

I tried $current_user = return redirect('/getuser'); but it's giving me an error - I don't know why specifically but I'm pretty sure you can't assign a returned response on a variable perhaps?

Reason why I'm using a different API on getting the user is because of Sessions. The api routes cannot read/store sessions properly (probably because they're stateless or something) so I placed that /getuser on the web routes which works perfectly. I could call the web "api" anywhere and it would give me the current user. Now however, I cannot reference the said current user within the api routes by doing session()->get()... since it wouldn't read sessions. My solution is to call that /getuser api I made on web routes and assign its returned response on a variable - which I have no idea how.

Is there anyway I could achieve something like that? Thanks a ton!

Upvotes: 1

Views: 6434

Answers (1)

Poldo
Poldo

Reputation: 1932

You can use guzzle in laravel when you need to call api in your controller.

use GuzzleHttp\Client;
class MyController extends Controller {

    public function show_user()
    {
        $client = new Client();
        $res = $client->request('GET', '/getuser', [
            'form_params' => [
                'KEY' => 'VALUE',
            ]
        ]);

        $result= $res->getBody();
        dd($result);

}

Read blog here

Upvotes: 2

Related Questions