Laravel is a popular PHP framework known for its simplicity and power. It allows developers to create robust and scalable backend services.
In this guide, we will walk through the process of creating, securing, and documenting a RESTful API using Laravel.
Step 1: Install Laravel
Before we begin, make sure you have Laravel installed on your local machine. To create a new Laravel project, run the following command:
composer create-project laravel/laravel laravel-restful-api
Go to the project directory:
cd laravel-restful-api
Step 2: Database configuration
Laravel supports many databases. I use Sqlite for this demo, but you can choose another. To configure yours, go to the .env file and set your database credentials.
DB_CONNECTION=sqlite
DB_DATABASE=../database/database.sqlite
SQLite databases are in one file on your filesystem. You can create a new SQLite database with the touch command in your terminal or manually:
touch database/database.sqlite
In Windows:
echo > database/database.sqlite
Step 3: Creating Models, Migrations, and Controllers
To build a simple API for managing blog posts, start by creating a migration, model, and controller for Post. You may need another controller for authentication AuthController, but you can write the authentication logic in the UserController.
php artisan make:model Post -m -c --api
The - api flag generates an API-specific controller without boilerplate methods for rendering views.
This single line of code will create the following routes:
GET /api/posts – List all posts
GET /api/posts/{id} – Get a specific post
POST /api/posts – Create a new post
PUT /api/posts/{id} – Update a post
DELETE /api/posts/{id} – Delete a post
This will create a model (Post.php) and a migration file in the database/migrations folder. Open the migration file and define the schema for the posts table.
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('author');
$table->mediumText('excerpt');
$table->longText('text');
$table->timestamps();
});
In the Post model, add the fillable property:
protected $fillable = ['title', 'author', 'excerpt', 'text'];
Now, run the migration:
php artisan migrate
Step 4: Defining Routes
Laravel lets you define API routes in routes/api.php. These routes are prefixed with /api. Define the routes for Post:
If you don't see the api.php file in the routes folder, you can either create it through the command line interface or just manually.
We've added the posts API resources to the sanctum middleware so we can check and filter HTTP requests coming into your app. To do this, you need to have the sanctum package installed. If you don't have it, just run this command to install it:
php artisan install:api
Next, you'll want to add the path to the api.php file to the app.php file in the bootstrap folder. Then, map it to the api name, as shown in the code below.
Step 5: Implementing the API Logic in the AuthController
I like to keep things organized and separated based on specific roles and functions, so I will create another AuthController that will handle the authentication logic.
php artisan make:controller AuthController
We also need to add HasApiTokens trait to the User model
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
Step 6: Let's add index, store, and show methods to the PostController to handle posts.
To test the newly create API that manages blog posts, I use Postman, which is an API platform for building and using APIs:
To log in, just use the URL below and add your email address and a valid password.
http://localhost:8000/api/login
After a successful log in attempt, you will a json response as show below:
{
"0": {
"ok": true,
"user": {
"id": 4,
"name": "Hamza Sehouli",
"email": "sehouli.test@gmail.com",
"email_verified_at": null,
"created_at": "2024-09-07T21:51:50.000000Z",
"updated_at": "2024-09-07T21:51:50.000000Z"
},
"token": "5|8vamsAP4WPkbctrecPnXymRYpkaiQU4AkBW2AwQq3f30e7d4"
},
"status": 200
}
As we added the API resources for posts to the sanctum:auth middleware in the api.php route file, we need to include a bearer token in the header to access the posts data.
For instance, to retrieve all posts using a GET request, we simply enter the URL below:
Bottom line
Laravel makes it easy to handle authentication with built-in systems and tools like Sanctum. Even when you're building authentication manually, Laravel's Auth facade, and middleware give you powerful tools to streamline the process of logging in, signing up.
Top comments (0)