Building REST APIs with PHP and Laravel
# 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.phpfile.
-
Understand the
apiResourcerouting 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:
The Magic Shortcut: Because Laravel adheres strictly to REST conventions, you can replace all 5 lines above with ONE line of code.
*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.
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
Now, inject it into the Controller:
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
Using the Resource in the Controller:
8. Best Practices
-
Use
findOrFail: Always useUser::findOrFail($id)instead ofUser::find($id)when fetching single resources. If the record does not exist,findOrFailthrows a ModelNotFoundException, which Laravel's global error handler automatically catches and converts into a perfect404 Not FoundJSON response.
9. Common Mistakes
-
Putting API Routes in
web.php: Laravel has two routing files.web.phpis for rendering HTML views and it automatically applies stateful Session Cookies and CSRF verification. If you put an API route inweb.php, POST requests will fail because APIs do not use CSRF tokens. ALWAYS put API routes inroutes/api.php.
10. Exercises
-
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
updatefunction in a Laravel API Controller. The client is targetingPUT /api/users/5. Write the conceptual code to find user #5 (ensuring a 404 is thrown if they don't exist), update theirnamewith the incoming$request->name, save the database record, and return a200 OKJSON response.
12. MCQs with Answers
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?
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 theapiResource 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.