I wrote this article as a complementary of the article about Laravel call route internally.
A- Get Laravel Bearer token:
Take a look at this link in Laravel 5.8.
As you see, there is a bearerToken() method on the Illuminate\Http\Request
object, which gets the bearer token from the request headers. (bearerToken() is available from Laravel version 5.2).
If you look at the Request class, you see that it is using InteractsWithInput Trait:
use Concerns\InteractsWithInput,
The logic behind this is in line 53 of InteractsWithInput Trait as follow:
/**
* Get the bearer token from the request headers.
*
* @return string|null
*/
public function bearerToken()
{
$header = $this->header('Authorization', ''); if (Str::startsWith($header, 'Bearer ')) {
return Str::substr($header, 7);
}
}
So you should just invoke this method to get the bearer token:
$token = $request->bearerToken();
And then get what you expect.
Before you continue with the rest of this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.
https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs
B- Set Laravel Bearer Token:
If you want to set a Bearer Token, you should follow this according to the Laravel document:
Your application’s API consumers may provide their API token as a Bearer
token in the Authorization
header of the request:
$response = $client->request('POST', '/api/user', [
'headers' => [
'Authorization' => 'Bearer '.$token,
'Accept' => 'application/json',
],
]);
Read more:
If you want to know more about bearer token read these answers.
Thank you for reading! If you enjoyed this article:
Clap it ! Share it! Follow Me in Medium!
Also I’d like to hear your opinion on this article. If you have any doubt, question or suggestion please leave a comment below.
Have a very wonderful day!