DEV Community

Adebayo Olukunle
Adebayo Olukunle

Posted on

Creating an API in Laravel

Laravel is a powerful PHP framework that provides a robust set of tools to build APIs efficiently. In this guide, we'll walk through the process of setting up and creating a RESTful API in Laravel, covering authentication, routing, controllers, and resource management.

Prerequisites

  • PHP
  • Composer
  • Laravel
  • MySQL/PostgreSQL
  • Postman or cURL for testing

Step 1: Install Laravel

To start, install Laravel using Composer:

composer create-project --prefer-dist laravel/laravel api_tutorial
cd api_tutorial
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up Database

Configure your .env file with your database details:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapi_db
DB_USERNAME=root
DB_PASSWORD=secret
Enter fullscreen mode Exit fullscreen mode

Run migrations to set up default tables:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a Model and Migration

Generate a model and migration for a sample Post resource:

php artisan make:model Post -m
Enter fullscreen mode Exit fullscreen mode

Modify the generated migration file in database/migrations/:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}

Enter fullscreen mode Exit fullscreen mode

Run the migration:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 4: Create a Controller

Generate a resource controller for the Post model:

php artisan make:controller PostController --api
Enter fullscreen mode Exit fullscreen mode

Modify app/Http/Controllers/PostController.php:

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

class PostController extends Controller
{
    public function index()
    {
        return response()->json(Post::all());
    }

    public function store(Request $request)
    {
        $post = Post::create($request->all());
        return response()->json($post, 201);
    }

    public function show(Post $post)
    {
        return response()->json($post);
    }

    public function update(Request $request, Post $post)
    {
        $post->update($request->all());
        return response()->json($post);
    }

    public function destroy(Post $post)
    {
        $post->delete();
        return response()->json(null, 204);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Define API Routes

Modify routes/api.php:

use App\Http\Controllers\PostController;

Route::apiResource('posts', PostController::class);
Enter fullscreen mode Exit fullscreen mode

Step 6: Test API Endpoints

Start the Server and Use Postman or cURL to test your endpoints:

php artisan serve
Enter fullscreen mode Exit fullscreen mode

GET all posts:

curl -X GET http://localhost/api/posts
Enter fullscreen mode Exit fullscreen mode

POST a new post:

curl -X POST http://localhost/api/posts -d "title=New Post&content=This is content" -H "Content-Type: application/json"
Enter fullscreen mode Exit fullscreen mode

GET a single post:

curl -X GET http://localhost/api/posts/1
Enter fullscreen mode Exit fullscreen mode

Update a post:

curl -X PUT http://localhost/api/posts/1 -d "title=Updated Post&content=Updated content" -H "Content-Type: application/json"
Enter fullscreen mode Exit fullscreen mode

DELETE a post:

curl -X DELETE http://localhost/api/posts/1
Enter fullscreen mode Exit fullscreen mode

Step 7: Implement Authentication

Laravel provides API authentication via Laravel Sanctum:

composer require laravel/sanctum

Publish Sanctumโ€™s configuration:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Enter fullscreen mode Exit fullscreen mode

Run migrations:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Ensure that Sanctum middleware is enabled in app/Http/Kernel.php:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Enter fullscreen mode Exit fullscreen mode

Use HasApiTokens in User.php:

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}
Enter fullscreen mode Exit fullscreen mode

Authentication Routes

Modify routes/api.php:

use App\Http\Controllers\AuthController;

Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);

Route::middleware('auth:sanctum')->group(function () {
    Route::get('user', [AuthController::class, 'user']);
    Route::post('logout', [AuthController::class, 'logout']);
});
Enter fullscreen mode Exit fullscreen mode

Authentication Controller

Create an authentication controller:

php artisan make:controller AuthController
Enter fullscreen mode Exit fullscreen mode

Modify AuthController.php:

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

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

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

    public function login(Request $request)
    {
        $user = User::where('email', $request->email)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }

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

    public function user(Request $request)
    {
        return response()->json($request->user());
    }

    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();
        return response()->json(['message' => 'Logged out']);
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

You've now built a secure Laravel API with authentication, CRUD operations, and routing. You can further enhance this by adding validation, pagination, and error handling to make it production-ready.

Top comments (0)