JustPaste
JustPaste
Tutorial 10 Maret 2026 1 menit baca 2.105 views Regi Pratama

Membuat REST API dengan Laravel 11: Panduan Lengkap

Laravel adalah framework PHP terpopuler untuk membangun API modern. Artikel ini memandu Anda membuat REST API dari nol.

Persiapan Project

composer create-project laravel/laravel api-project
cd api-project
php artisan key:generate

Membuat Model dan Migration

php artisan make:model Article -mrc

Contoh Migration

Schema::create('articles', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->foreignId('user_id')->constrained();
    $table->timestamps();
});

Route API

Route::apiResource('articles', ArticleController::class)
    ->middleware('auth:sanctum');

Response JSON Konsisten

Selalu gunakan Resource class untuk konsistensi response:

php artisan make:resource ArticleResource

Testing dengan Pest

it('can create article', function () {
    $user = User::factory()->create();
    $response = $this->actingAs($user)
        ->postJson('/api/articles', ['title' => 'Test', 'content' => 'Content']);
    $response->assertCreated();
});

Bagikan artikel ini: