πŸ“ 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?

🌍 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:


πŸ“ 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

πŸ“Œ 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! πŸš€