📁 Laravel API Project Folder Structure (Simplified)
laravel-api-project/ ├── app/ ├── bootstrap/ ├── config/ ├── database/ ├── public/ ├── resources/ ├── routes/ │ └── api.php ← 🟢 Define your API routes here ├── storage/ └── vendor/
📘 What is an API?
API stands for Application Programming Interface. It allows two applications to communicate with each other. In Laravel, APIs are typically defined in routes/api.php
and return JSON data.
✅ Real-Life Analogy:
Think of an API as a restaurant menu. You (the frontend) choose what you want, and the kitchen (backend) delivers it. The waiter (API) is the communicator between the two.
💡 Why Are APIs Important?
- 🔄 Separate frontend and backend logic
- 🔗 Let mobile apps, websites, and other systems connect
- 🔒 Offer controlled access to data and services
- 🔧 Reusable: One backend can serve many frontends
🌍 What is CORS?
CORS (Cross-Origin Resource Sharing) is a browser security feature that blocks frontend JavaScript from calling an API on a different domain/port unless that API explicitly allows it.
⚠️ Without CORS
When using fetch()
or Axios from a frontend (like React or JS), the browser will block the request if CORS headers are not present.
Example error:
Access to fetch at 'http://localhost:8000/api/hello' from origin 'http://localhost:3000' has been blocked by CORS policy.
❌ Example: Laravel API imports
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request ;
Route::get('/hello', function () {
return response()->json(['message' => 'Hello']);
});
Calling this from a React/JS frontend on a different port will result in a CORS error.
✅ Example: Laravel API With Inline CORS (Option 2)
Route::get('/hello', function () {
return response()
->json(['message' => 'Hello with CORS'])
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
});
Now the API will work from any frontend like React, Vue, or simple HTML/JS.
📌 Summary
- ✅ Use
routes/api.php
for Laravel APIs
- ✅ Use
response()->json(...)
to return data
- ✅ Add inline CORS headers to allow frontend access
- ✅ For advanced control, prefer middleware-based CORS later
💡 Tip: Use inline CORS for small or demo projects. Use middleware for scalable and secure applications.
🌐 Laravel API Tutorial: Hello World, Add Two Numbers, and CORS
This tutorial covers:
- ✅ A Hello World API in Laravel
- ✅ An API to Add Two Numbers
- ✅ Option 2: Adding CORS headers inline for specific routes
📁 Location: routes/api.php
🚀 1. Hello World API
This route returns a simple JSON message. CORS headers are included inline:
use Illuminate\Support\Facades\Route;
Route::get('/hello', function () {
return response()
->json(['message' => 'Hello from Laravel API with CORS'])
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
});
➕ 2. Add Two Numbers API
This route accepts two numbers via POST and returns their sum:
use Illuminate\Http\Request;
Route::post('/add', function (Request $request) {
$num1 = $request->input('num1');
$num2 = $request->input('num2');
$sum = $num1 + $num2;
return response()
->json([
'num1' => $num1,
'num2' => $num2,
'sum' => $sum
])
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
});
⚠️ 3. Handle OPTIONS Preflight Requests
To support frontend frameworks like React, add this route for OPTIONS requests:
Route::options('/{any}', function () {
return response('', 204)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
})->where('any', '.*');
🧪 Testing the APIs
- Use Postman or fetch() in JavaScript/React
- Send requests to:
GET http://localhost:8000/api/hello
POST http://localhost:8000/api/add
- POST JSON body example:
{ "num1": 10, "num2": 15 }
📌 Summary
Route | Method | Description |
---|---|---|
/api/hello |
GET | Returns Hello message |
/api/add |
POST | Returns the sum of two numbers |
💡 Tip: Use inline CORS headers for small projects or testing. For production, switch to middleware-based CORS handling.
Happy coding! 🚀
0 Comments