How to make a Laravel app that has an API and authentication

In this post, I will show you how to create a simple Laravel app that exposes a RESTful API and uses Laravel Sanctum for authentication. Here are the steps:

  1. Install Laravel and create a new project. You can use Composer or Laravel Installer to install Laravel on your machine. To create a new project, run the following command in your terminal:
laravel new laravel-api
  1. Install Laravel Sanctum and configure it. Laravel Sanctum is a package that provides a simple and lightweight way to authenticate your API requests using tokens. To install it, run the following command in your terminal:
composer require laravel/sanctum

Then, publish the Sanctum configuration and migration files by running:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

Next, run the migration to create the personal_access_tokens table in your database:

php artisan migrate

Finally, add the Laravel\Sanctum\HasApiTokens trait to your User model:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    // ...
}
  1. Create an API controller and routes. To handle the API requests, you need to create a controller that defines the logic for each endpoint. For example, you can create a PostController that allows users to CRUD posts. To generate a controller, run the following command in your terminal:
php artisan make:controller PostController --api

This will create a PostController class in the app/Http/Controllers directory with some boilerplate code. You can modify the methods according to your needs. For example, you can use the Post model to interact with the posts table in your database.

Next, you need to define the routes for your API endpoints in the routes/api.php file. For example, you can use the Route::apiResource method to create a set of RESTful routes for the PostController:

<?php

use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;

Route::apiResource('posts', PostController::class);

This will create the following routes:

MethodURIAction
GET/api/postsindex
POST/api/postsstore
GET/api/posts/{post}show
PUT/PATCH/api/posts/{post}update
DELETE/api/posts/{post}destroy
  1. Protect your API routes with Sanctum middleware. To ensure that only authenticated users can access your API endpoints, you need to apply the auth:sanctum middleware to your routes. You can do this by chaining the middleware method to your route definitions:
<?php

use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;

Route::apiResource('posts', PostController::class)->middleware('auth:sanctum');

Alternatively, you can apply the middleware in your controller’s constructor:

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    // ...
}
  1. Test your API and authentication using Postman or any other tool. To test your API and authentication, you need to use a tool like Postman that allows you to send HTTP requests and inspect the responses. First, you need to register a user and get a token from Sanctum. To do this, you can create a route that handles user registration and token creation in your routes/api.php file:
<?php

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Route;

Route::post('register', function (Request $request) {
    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => Hash::make($request->password),
    ]);

    $token = $user->createToken('my-app-token')->plainTextToken;

    return response()->json(['user' => $user, 'token' => $token]);
});

Then, you can use Postman to send a POST request to /api/register with some user data in JSON format:

{
    "name": "John Doe",
    "email": "[email protected]",
    "password": "secret"
}

You should get a response like this:

{
    "user": {
        "id": 1,
        "name": "John Doe",
        "email": "[email protected]",
        "email_verified_at": null,
        "created_at": "2023-07-18T12:34:56.000000Z",
        "updated_at": "2023-07-18T12:34:56.000000Z"
    },
    "token": "1|yfjw8X9l7Q0HmY9oq0z2x8V4W7wJLk5kP6pKQbJi"
}

The token is a plain text string that consists of two parts separated by a pipe (|). The first part is the token ID, and the second part is the token value. You need to use the token value as the bearer token in your subsequent API requests. To do this, you can set the Authorization header to Bearer {token} in Postman.

Now, you can test your API endpoints using Postman. For example, you can send a GET request to /api/posts to get all the posts. You should get a response like this:

[
    {
        "id": 1,
        "title": "Hello World",
        "content": "This is my first post",
        "user_id": 1,
        "created_at": "2023-07-18T12:45:67.000000Z",
        "updated_at": "2023-07-18T12:45:67.000000Z"
    },
    {
        "id": 2,
        "title": "Another Post",
        "content": "This is another post",
        "user_id": 1,
        "created_at": "2023-07-18T12:46:78.000000Z",
        "updated_at": "2023-07-18T12:46:78.000000Z"
    }
]

You can also send other requests to create, update, or delete posts using the corresponding methods and URIs.

That’s it! You have successfully created a Laravel app that has an API and authentication using Laravel Sanctum. I hope you enjoyed this blog post and learned something new. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading! 😊