PHP / Laravel / Token / Request

How to get the authentication token from the Request in Laravel?

Get Bearer token from a request

Mohammad Rakibul Haider
3 min readMar 6, 2021

When working with an API often you will hear about authentication tokens. Today, I am not going to describe what this token is or how to generate it. I am assuming you already know what an authentication token is. This tutorial is all about how to get that authentication token from a request.

There are two methods that we can use to get the authentication token from the request and they are:

BearerToken Method

This method returns the bearer token from the request headers. If the bearer token is not found then it returns null.

Write the above code in the api.php file which is located in the routes folder at your Laravel project. To make this example simple we are using a closure in the routes get method.

Now it’s time for testing and we can do it by using Postman. If you do not have Postman then download it from here. After finishing the download, install it and then open it.

Now, select HTTP Verb Get” from the drop-down. If you are running the project using the artisan command: php artisan serve, then write “localhost:8000/api” in the URL section without the quotation mark.

Suppose, our token is “xyz” and we need to add it in the Authorization Header. To do this click on the Headers tab and add key Authorization and value “Bearer xyz” without the quotes like the picture below.

After that, click on the send button and you will get the below output if everything is working fine.

Header Method

The header method retrieves headers based on the key and returns the value of that key. If the header is not present, it returns null. To avoid null, we can use the second parameter which is the default value of that key. Finally, write the below code in the “api.php” file in the routes folder.

In the code above, at first, we get the Authorization header from the request object, check if the token starts with Bearer. If it starts with Bearer, get the token from that header value and return it. At last, test it using Postman like the previous one.

Summary

From the above two examples, we observe that the bearerToken() method is the most concise and easy way to retrieve a token from the request.

--

--