In Laravel 11, Passport Auth package allows users to create login, register REST API by token based authentication.
Let’s start installing and configuring Passport auth to create token based authentication:
Step 1 – Install Laravel and Create a New Project
Run the following composer command to install and create new laravel project:
composer create-project --prefer-dist laravel/laravel passport-auth-example
Step 2: Install Laravel Passport
Install passport auth to create rest api:
cd passport-auth-example
php artisan install:api --passport
Step 3 – Configure Passport
Edit your user.php
model from app/models folder, and add the HasApiTokens
trait:
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
// Rest of your model code...
}
Edit config/auth.php
file and API driver:
[
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Step 4 – Set Up Database
Edit .env file and configure database details in it:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here
Run migration command to create tables into your configured database:
php artisan serve
Step 5 – Create API Routes
Next, define the routes for your API endpoints. Open your api.php
file located at routes/api.php
and define your routes:
use App\Http\Controllers\API\PassportAuthController;
Route::post('register', [PassportAuthController::class, 'register']);
Route::post('login', [PassportAuthController::class, 'login']);
Route::middleware('auth:api')->group(function () {
Route::get('get-user', [PassportAuthController::class, 'userInfo']);
});
Step 6 – Create Controller and Method
Create a controller file by using the following command:
php artisan make:controller Api\PassportAuthController
Now implement authentication methods into it to handle login, registration and user detail functionality from database:
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Models\User;
class AuthController extends Controller
{
/**
* Registration Req
*/
public function register(Request $request)
{
$this->validate($request, [
'name' => 'required|min:4',
'email' => 'required|email',
'password' => 'required|min:8',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$token = $user->createToken('PassportAuth')->accessToken;
return response()->json(['token' => $token], 200);
}
/**
* Login Req
*/
public function login(Request $request)
{
$data = [
'email' => $request->email,
'password' => $request->password
];
if (auth()->attempt($data)) {
$token = auth()->user()->createToken('PassportAuth')->accessToken;
return response()->json(['token' => $token], 200);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
public function userInfo()
{
$user = auth()->user();
return response()->json(['user' => $user], 200);
}
}
Step 7 – Test
Run artisan serve command to start the application server:
php artisan serve
And open Postman application and call these API for testing:
Register a User:
- Open Postman.
- Set the request type to
POST
. - Enter
http://yourdomain.com/api/register
in the address bar (replaceyourdomain.com
with your actual domain). - Go to the
Body
tab. - Choose
x-www-form-urlencoded
and selectJSON
. - Enter the user registration data in JSON format, including
name
,email
, andpassword
. - Click on the
Send
button to register the user.
Login:
- Set the request type to
POST
. - Enter the URL of your Laravel application followed by
/api/login
(e.g.,http://yourdomain.com/api/login
). - Go to the
Body
tab. - Select
and set the format tox-www-form-urlencoded
JSON
. - Enter the user’s credentials (email and password) in JSON format.
- Click on the
Send
button to login. You will receive a token in the response if the login is successful.
Get User Info:
- Set the request type to
GET
. - Enter the URL of your Laravel application followed by
/api/get-user
(e.g.,http://yourdomain.com/api/get-user
). - Go to the
Headers
tab. - Add a new header with the key
Authorization
and the valueBearer <token>
, where<token>
is the token obtained during the login process. - Click on the
Send
button to get the user information.