Laravel is a popular PHP framework that makes it easier for developers to build robust and secure web applications. In this tutorial, we will be building a REST API in Laravel 9 that uses Passport for authentication. Before we dive into the tutorial, let's go over what a REST API is and what Passport does. A REST API (Representational State Transfer API) is a web API that uses HTTP methods like GET, POST, PUT, DELETE to interact with data. Passport is a Laravel package that makes it easy to implement OAuth2 authentication in your application. Now, let's get started.
To install Laravel 9, you will need to have Composer installed on your machine. Once you have Composer installed, open a terminal and run the following command:
composer create-project --prefer-dist laravel/laravel laravel9-rest-api
To install Passport, run the following command in your terminal:
composer require laravel/passport
Next, we need to run migrations to create the necessary tables in the database. Run the following command in your terminal:
php artisan migrate
We need to create client IDs and secrets for our API. Run the following command in your terminal to create the clients:
php artisan passport:client
Now, we need to configure Passport. First, we need to add the following code to the config/auth.php file:
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Next, we need to add the following code to the app/Providers/AuthServiceProvider.php file:
use Laravel\Passport\Passport;
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
Next, we need to define the models and controllers for our API. First, let's create a User model. Run the following command in your terminal:
php artisan make:model User -m
Then, add the following code to the app/User.php file:
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
Next, let's create a controller for our API. Run the following command in your terminal:
php artisan make:controller API/UserController
Next, we need to define the API routes for our application. Add the following code to the routes/api.php file:
Route::post('register', 'API\UserController@register');
Route::post('login', 'API\UserController@login');
Route::middleware('auth:api')->group(function(){
Route::get('user', 'API\UserController@details');
});
Now, we need to implement user registration and login in the UserController. Add the following code to the app/Http/Controllers/API/UserController.php file:
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
return response()->json(['success'=>$success], 200);
}
public function login()
{
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], 200);
}
else{
return response()->json(['error'=>'Unauthorized'], 401);
}
}
Finally, we need to implement the user details endpoint. Add the following code to the app/Http/Controllers/API/UserController.php file:
public function details()
{
$user = Auth::user();
return response()->json(['success' => $user], 200);
}
That's it! You have successfully built a REST API in Laravel 9 that uses Passport for authentication. You can test the API using Postman or any other API testing tool. In conclusion, Laravel makes it easy for developers to build secure and robust web applications. With the help of Passport, implementing OAuth2 authentication in your laravel application is a breeze. I hope you found this tutorial helpful.