Introduction
In this article you will learn about, Create Laravel 11 API with PostgreSQL. Laravel is a powerful PHP framework that simplifies web application development. In this guide, we will learn how to create a Laravel 11 API and connect it to a PostgreSQL database. We will cover installation, configuration, and implementing CRUD operations step by step.
1. Setting Up Laravel 11
Step 1: Install Laravel 11
Before we begin, ensure Composer is installed. Then, run the following command to create a new Laravel project:
composer create-project laravel/laravel laravel-11-example
Once the installation is complete, navigate to the project directory:
cd laravel-11-example
2. Configuring PostgreSQL Database
Step 2: Update Database Configuration
Modify the database configuration in config/database.php
:
'default' => env('DB_CONNECTION', 'pgsql'),
Next, update the .env
file with your PostgreSQL credentials:
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=laravel_11
DB_USERNAME=postgres
DB_PASSWORD=postgres
Now, create the database in PostgreSQL:
CREATE DATABASE laravel_11;
3. Creating the Model and Migration
Step 3: Generate Model, Migration, and Controller
Use the following command to generate all required files:
php artisan make:model Todo -a
This command creates a model, migration, factory, and controller.
Step 4: Edit the Migration File
Modify the migration file in database/migrations/
to define the structure of the todos table:
Schema::create('todos', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->boolean('status');
$table->timestamps();
});
Run the migration to apply changes to the database:
php artisan migrate
4. Implementing API Endpoints
Step 5: Create the Controller
Open the app/Http/Controllers/TodoController.php
file and implement CRUD operations:
namespace App\Http\Controllers;
use App\Models\Todo;
use Illuminate\Http\Request;
class TodoController extends Controller
{
public function index()
{
return response()->json(Todo::all(), 200);
}
public function store(Request $request)
{
$todo = Todo::create($request->all());
return response()->json($todo, 201);
}
public function show($id)
{
return response()->json(Todo::findOrFail($id), 200);
}
public function update(Request $request, $id)
{
$todo = Todo::findOrFail($id);
$todo->update($request->all());
return response()->json($todo, 200);
}
public function delete($id)
{
Todo::destroy($id);
return response()->json(['message' => 'Todo deleted'], 200);
}
}
5. Defining API Routes
Step 6: Add Routes in routes/api.php
Define the API endpoints in Laravel’s routing system:
use App\Http\Controllers\TodoController;
Route::get('/todos', [TodoController::class, 'index']);
Route::post('/todos', [TodoController::class, 'store']);
Route::get('/todos/{id}', [TodoController::class, 'show']);
Route::put('/todos/{id}', [TodoController::class, 'update']);
Route::delete('/todos/{id}', [TodoController::class, 'delete']);
6. Handling Exceptions
Step 7: Register Exception Handling
Modify app/Exceptions/Handler.php
to return custom error messages when invalid routes are accessed:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
return response()->json(['success' => false, 'message' => 'Invalid route'], 404);
});
}
7. Running the Application
Step 8: Start Laravel Server
Now, start the Laravel development server using the command:
php artisan serve
This will launch the server at http://127.0.0.1:8000
, and you can start testing the API.
8. Testing API Endpoints
To test the API, use Postman, cURL, or Laravel’s built-in test suite. Here are some examples:
Fetch all Todos:
curl -X GET http://127.0.0.1:8000/api/todos
Create a Todo:
curl -X POST http://127.0.0.1:8000/api/todos \
-H "Content-Type: application/json" \
-d '{"name":"Learn Laravel","status":false}'
Update a Todo:
curl -X PUT http://127.0.0.1:8000/api/todos/1 \
-H "Content-Type: application/json" \
-d '{"name":"Learn Laravel 11","status":true}'
Delete a Todo:
curl -X DELETE http://127.0.0.1:8000/api/todos/1
Conclusion
Congratulations! You have successfully created a Laravel 11 API connected to a PostgreSQL database. In this guide, we covered installation, database configuration, migrations, API endpoints, and exception handling. With this foundation, you can enhance your API by adding authentication, validation, and advanced features. Keep exploring Laravel, and happy coding!
Thanks for reading, Create Laravel 11 API with PostgreSQL.