Laravel get Bearer token from a request

Image for post
Image for post

I wrote this article as a complementary of the article about Laravel call route internally.

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);
}
}
Image for post
Image for post

So you should just invoke this method to get the bearer token:

$token = $request->bearerToken();

And then get what you expect.

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',
],
]);

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!

Written by

Web geek, Self-taught full-stack web developer, Learning Python, Laravel, Vuejs, UX/UI design, Nuclear Physicist PhD

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store