Laravel

Building a REST API with Laravel from Scratch

From routes to tidy JSON responses: we build a simple product API complete with validation.

C Codesakura 1 min 3 comments

Contents

A REST API lets other apps (a mobile app, a React frontend, or a third-party service) talk to yours. In this part we build a simple product API: list, create, and delete.

Setting up the routes

Laravel ships with Route::apiResource, which registers every CRUD route at once. Add this to routes/api.php:

Route::apiResource('products', ProductController::class);

Writing the controller

The controller simply returns models. Laravel turns them into JSON for you.

public function index()
{
  return Product::latest()->paginate(20);
}

Next steps

The API is still open to anyone. In the next part we add token authentication so only registered users can create products.

Part of a series

Laravel from Scratch
  1. 1Setting Up Your First Laravel Project
  2. 2Mengenal Routing dan Controller di Laravel
  3. 3Building a REST API with Laravel from Scratch
Share X Facebook WhatsApp Telegram

3 comments

Log in to join the conversation. Log in

D

Dewi S.

Ditunggu lanjutannya.

R

Rizky A.

Penjelasannya runtut, langsung saya coba dan jalan. Terima kasih!

C

Codesakura Author

Senang bisa membantu. Kalau ada yang macet, tulis saja di sini.

Related tutorials

Laravel

Mengenal Routing dan Controller di Laravel

1 min Series · Part 2 of 3

Laravel

Setting Up Your First Laravel Project

1 min Series · Part 1 of 3

Laravel

Upload File yang Aman di Laravel

1 min