0
votes

I just use the default api that laravel provided with a little change when i make the project which is

    Route::middleware('auth:api')->get('/user', function (Request $request) {
    return User::all();
});

I already make api_token in user table and fill it with some token When i use postman the api works Postman

But when i write the request code in the controller it always return null

$token = 'abcde';
$request = Request::create('/api/user', 'GET', [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$token,
]);
$response = json_decode(Route::dispatch($request)->getContent());
dd($response);

The api works if i dont use middleware('auth:api') Any suggestion?

EDIT I tried to use Guzzle and get this error Guzzle Error

1
what auth you are using passport jwtKamlesh Paul
It's the default laravel auth:api. But i use jwt just to generate the random token when the user register an account.Ricky Gideon
then use jwt default one will not work like this u can read this medium.com/@danielalvidrez/…Kamlesh Paul
But it still return null even if i use a hardcoded token like the one in the postman picture above.Ricky Gideon
you can't set token like thatKamlesh Paul

1 Answers

0
votes

Try with Guzzle

$client = new \GuzzleHttp\Client();
$token = 'abcde';
$request = $client->request('api/user', 'GET', [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$token,
        ]);
$response = $request->getBody()->getContents();
$response = json_decode($request,true);
dd($response);