What are you looking for?
What are you looking for?
Laravel makes it incredibly easy to create RESTful APIs with built-in routing, controllers, and model integration. In this guide, we'll build a basic Product API from scratch — ideal for SPAs, mobile apps, or third-party consumers.
Ensure the following before you begin:
Use Composer to create a fresh Laravel installation:
composer create-project --prefer-dist laravel/laravel myApiProject cd myApiProject
Update your .env file with valid DB credentials:
DB_DATABASE=your_database DB_USERNAME=your_username DB_PASSWORD=your_password
Then run migrations:
php artisan migrate
Generate the model and its migration:
php artisan make:model Product -m
Now define the schema in the migration file:
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->decimal('price', 8, 2);
$table->timestamps();
});
Then run:
php artisan migrate
Generate a RESTful controller using:
php artisan make:controller ProductController --api
Open routes/api.php and register this:
use App\Http\Controllers\ProductController;
Route::apiResource('products', ProductController::class);
Edit app/Http/Controllers/ProductController.php like this:
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index()
{
return Product::all();
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string',
'description' => 'nullable|string',
'price' => 'required|numeric',
]);
$product = Product::create($validated);
return response()->json($product, 201);
}
public function show($id)
{
return Product::findOrFail($id);
}
public function update(Request $request, $id)
{
$product = Product::findOrFail($id);
$validated = $request->validate([
'name' => 'sometimes|required|string',
'description' => 'nullable|string',
'price' => 'sometimes|required|numeric',
]);
$product->update($validated);
return response()->json($product);
}
public function destroy($id)
{
Product::destroy($id);
return response()->json(null, 204);
}
}
You can use Postman, Insomnia, or cURL to test:
GET /api/products → List all products
POST /api/products → Create a new product
GET /api/products/{id} → Retrieve a product
PUT /api/products/{id} → Update a product
DELETE /api/products/{id} → Delete a product
You now have a fully working RESTful API in Laravel. Laravel’s built-in tooling — from routing to controllers and validation — makes it quick and clean to deliver robust backend APIs. Consider adding authentication with Sanctum or Passport if needed.