Skip to main content
REST API Design Tutorial
CHAPTER 16 Beginner

Building REST APIs with PHP and Laravel

Updated: May 14, 2026
35 min read

# CHAPTER 16

Building REST APIs with PHP and Laravel

1. Introduction

While Express.js requires you to wire together routing, parsing, and error handling manually, Laravel (the premier PHP framework) takes a completely different approach. Laravel is a "batteries-included" framework. It has built-in opinions on exactly how REST APIs should be structured. By adhering to Laravel's conventions, you can build incredibly robust, highly secure REST APIs in a fraction of the time. In this chapter, we will translate our REST concepts into Laravel's elegant syntax, exploring API Routes, Eloquent Models, API Resources, and Form Requests.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define API routes in Laravel's specific api.php file.
  • Understand the apiResource routing shortcut.
  • Create RESTful Controllers returning JSON responses.
  • Implement Form Request Validation.
  • Utilize Eloquent API Resources for data serialization.

3. Beginner-Friendly Explanation

Imagine building a house.
  • Node.js/Express: You drive to the hardware store, buy the wood, the nails, the pipes, and the electrical wire. You measure everything yourself and build the house from scratch. It's highly customizable, but it takes time.
  • Laravel: You buy a high-end prefabricated home. The walls are already built. The plumbing is already connected. The electrical panel is already wired. You just arrange the furniture.

Laravel pre-configures JSON parsing, CORS, Error Handling, and Database connections out of the box so you can focus entirely on your API's business logic.

4. Step 1: API Routing (routes/api.php)

In Laravel, web pages and API routes are strictly separated. API routes go in routes/api.php. Laravel automatically prefixes every route in this file with /api, and automatically applies stateless middleware (no sessions).

Manual Routing:

php
1234567
use App\Http\Controllers\UserController;

Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::get('/users/{id}', [UserController::class, 'show']);
Route::put('/users/{id}', [UserController::class, 'update']);
Route::delete('/users/{id}', [UserController::class, 'destroy']);

The Magic Shortcut: Because Laravel adheres strictly to REST conventions, you can replace all 5 lines above with ONE line of code.

php
1
Route::apiResource('users', UserController::class);

*This single line automatically generates all 5 standard REST endpoints mapped to the correct HTTP verbs!*

5. Step 2: The Controller (app/Http/Controllers/UserController.php)

Laravel uses the Eloquent ORM to interact with the database. Notice how we don't need to manually parse req.body or call JSON.stringify(). Laravel handles the JSON serialization automatically when you return an Eloquent Model.
php
12345678910111213141516171819202122232425262728293031
namespace App\Http\Controllers;

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

class UserController extends Controller
{
    // GET /api/users
    public function index() {
        return User::all(); // Laravel automatically returns 200 OK + JSON Array!
    }

    // POST /api/users
    public function store(Request $request) {
        $user = User::create($request->all());
        return response()->json($user, 201); // Return 201 Created
    }

    // GET /api/users/{id}
    public function show($id) {
        // If ID 99 doesn't exist, findOrFail automatically returns 
        // a 404 Not Found JSON error. No manual "if" statements needed!
        return User::findOrFail($id); 
    }

    // DELETE /api/users/{id}
    public function destroy($id) {
        User::destroy($id);
        return response()->json(null, 204); // Return 204 No Content
    }
}

6. Step 3: Input Validation (Form Requests)

As discussed in Chapter 9, validation is critical. Laravel extracts validation logic entirely out of the Controller into a separate file called a Form Request.

php artisan make:request StoreUserRequest

php
12345678
// app/Http/Requests/StoreUserRequest.php
public function rules() {
    return [
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|string|min:8'
    ];
}

Now, inject it into the Controller:

php
123456
// If the data fails the rules above, this function NEVER runs. 
// Laravel automatically intercepts it and returns a 422 JSON Error.
public function store(StoreUserRequest $request) {
    $user = User::create($request->validated());
    return response()->json($user, 201);
}

7. Step 4: Data Serialization (API Resources)

Never return raw database rows to an API client (it leaks passwords!). Laravel uses API Resources to cleanly transform the database model into secure JSON.

php artisan make:resource UserResource

php
123456789
// app/Http/Resources/UserResource.php
public function toArray($request) {
    return [
        'id' => $this->id,
        'full_name' => $this->name,
        // Password is intentionally omitted!
        'joined' => $this->created_at->format('Y-m-d') 
    ];
}

Using the Resource in the Controller:

php
1234
public function show($id) {
    $user = User::findOrFail($id);
    return new UserResource($user); // Transforms the data before sending!
}

8. Best Practices

  • Use findOrFail: Always use User::findOrFail($id) instead of User::find($id) when fetching single resources. If the record does not exist, findOrFail throws a ModelNotFoundException, which Laravel's global error handler automatically catches and converts into a perfect 404 Not Found JSON response.

9. Common Mistakes

  • Putting API Routes in web.php: Laravel has two routing files. web.php is for rendering HTML views and it automatically applies stateful Session Cookies and CSRF verification. If you put an API route in web.php, POST requests will fail because APIs do not use CSRF tokens. ALWAYS put API routes in routes/api.php.

10. Exercises

  1. 1. Explain the primary advantage of utilizing Laravel's apiResource() routing method over defining each route individually.

11. Coding Challenges

  • Challenge: You are writing the update function in a Laravel API Controller. The client is targeting PUT /api/users/5. Write the conceptual code to find user #5 (ensuring a 404 is thrown if they don't exist), update their name with the incoming $request->name, save the database record, and return a 200 OK JSON response.

12. MCQs with Answers

Question 1

In Laravel, which dedicated file must be used to define REST API routes to ensure they are properly prefixed with /api and utilize stateless middleware?

Question 2

When utilizing Laravel's apiResource('photos', PhotoController::class) method, how many RESTful endpoints are automatically generated and mapped to the controller?

13. Interview Questions

  • Q: Explain how Laravel handles API payload validation using Form Requests. What happens under the hood if an incoming JSON payload violates a validation rule defined in a Form Request?
  • Q: Compare and contrast building a REST API in Node.js/Express versus PHP/Laravel. In what scenarios would a "batteries-included" framework like Laravel be advantageous over a minimalist framework like Express?

14. FAQs

Q: How do I handle authentication in a Laravel API? A: Laravel provides a massive, pre-built package called Laravel Sanctum. It instantly provides secure JWT API token generation, password hashing, and route protection middleware with almost zero manual configuration required.

15. Summary

In Chapter 16, we explored the elegance of building REST APIs with Laravel. We leveraged the apiResource routing shortcut to generate compliant endpoints instantly. We observed how Eloquent controllers seamlessly convert PHP objects to JSON responses without manual serialization logic. Finally, we emphasized the necessity of using Form Requests to automate input validation and API Resources to securely shape our outgoing JSON, guaranteeing that passwords and sensitive database fields never leak to the public internet.

16. Next Chapter Recommendation

Your Express and Laravel APIs are written. But how do you prove they work without building a frontend React app? Proceed to Chapter 17: API Testing with Postman.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·