How to Create Laravel 11 API with PostgreSQL Database

Hello, laravel web developers! In this article, we'll see how to create laravel 11 API with the PostgreSQL database. Here, we'll create API in laravel 11. Today, we'll walk you through the process of creating a simple API using Laravel 11 and connecting it to a PostgreSQL database.

First, let’s make sure we have everything set up. We'll need Laravel 11 installed on our machine, and of course, a PostgreSQL database ready to go. Don’t worry if you don’t have these yet; I'll guide you through the installation process.

Once we’re all set up, we’ll dive into creating our API, which will allow us to perform basic CRUD (Create, Read, Update, Delete) operations on our database.

Laravel 11 creates API with PostgreSQL

laravel 11 create api with postgresql

 

Step 1: Install Laravel 11 Application

In this step, we'll create a laravel 11 application using the following command.

composer create-project laravel/laravel laravel-11-example

 

Step 2: Configure the database

In the database.php file within the app/config folder, the default connection will need to be changed.

app/config/database.php

'default' => env('DB_CONNECTION', 'pgsql')

.env

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=laravel_11
DB_USERNAME=postgres
DB_PASSWORD=postgres
DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:5432/laravel_11

 

Step 3: Create Model

Next, we'll create a model and migration using the following command.

php artisan make:model Todo -a

app/Models/Todo.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Todo extends Model
{
    use HasFactory;
    use HasUuids;

    protected $table = 'todos';
    protected $primaryKey = 'id';
    protected $fillable = ['name', 'status'];
    protected $casts = ["id" => "string"];
}

Create a new file for the responses that will be generated from the API.

touch TodoResponse.php

app/Models/TodoResponse.php

<?php

namespace App\Models;

class TodoResponse
{
  public bool $success;
  public string $message;
  public $payload;

  public function __construct(bool $success, string $message, $payload)
  {
    $this->success = $success;
    $this->message = $message;
    $this->payload = $payload;
  }

  public function to_json()
  {
    $res = [
      "success" => $this->success,
      "message" => $this->message,
      "payload" => $this->payload
    ];
    return $res;
  }
}

 

Step 5: Edit the migration file

Then, edit the migration file and add the required fields to the migration file.

Migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('todos', function (Blueprint $table) {
            $table->uuid("id");
            $table->string("name");
            $table->boolean("status");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('todos');
    }
};

Log into PostgreSQL through the terminal by typing

psql

If credentials are needed then add it. Then run the SQL command

CREATE DATABASE laravel_11;

In the root folder run the command to migrate the files to the database

php artisan migrate

Look at the database to see if the tables have loaded by using the command

\c laravel_11
\d
\d todos
\dt todos
SELECT * FROM todos;

 

Step 7: Create the controllers

Now, we'll create a TodoController.php file and add the following function to that file.

app/Http/Controllers/TodoController.php

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Todo;
use App\Models\TodoResponse;
use Ramsey\Uuid\Uuid;

class TodoController extends Controller
{
    public function index()
    {
        try {
            $todos = Todo::orderBy("updated_at", "desc")->get();
            $res = new TodoResponse(true, "Got todos", $todos);
            return response($res->to_json(), 200, ["Content-Type" => "application/json"]);
        } catch (\Exception $e) {
            $res = new TodoResponse(false, "Invalid request", $e->getMessage());
            return response($res->to_json(), 500, ["Content-Type" => "application/json"]);
        }
    }

    public function store()
    {
        try {
            $todo = new Todo();
            $todo->id = Uuid::uuid4();
            $todo->name = request("name");
            $todo->status = request("status");
            $data = $todo->saveOrFail();

            if (!$data) {
                $res = new TodoResponse(false, "Invalid request", null);
                return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
            }
            $res = new TodoResponse(true, "Created todo", $todo);
            return response($res->to_json(), 201, ["Content-Type" => "application/json"]);
        } catch (\Exception $e) {
            $res = new TodoResponse(false, "Invalid request", $e->getMessage());
            return response($res->to_json(), 500, ["Content-Type" => "application/json"]);
        }
    }

    public function show($id)
    {
        try {
            $todo = Todo::query()->where("id", "=", $id)->get();

            if (!count($todo)) {
                $res = new TodoResponse(false, "Invalid request", null);
                return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
            }
            $res = new TodoResponse(true, "Got todo", $todo);
            return response($res->to_json(), 200, ["Content-Type" => "application/json"]);
        } catch (\Exception $e) {
            $res = new TodoResponse(false, "Invalid request", $e->getMessage());
            return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
        }
    }

    public function update($id)
    {
        try {
            $todo = Todo::query()->where("id", "=", $id)->get();

            if (!count($todo)) {
                $res = new TodoResponse(false, "Invalid request", null);
                return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
            }

            $updated_todo = new Todo();
            $updated_todo->id = $id;
            $updated_todo->name = request("name");
            $updated_todo->status = request("status");

            $result = Todo::query()->where("id", "=", $id)->update([
                'id' => $id,
                'name' => $updated_todo->name,
                'status' => $updated_todo->status
            ]);

            if (!$result) {
                $res = new TodoResponse(false, "Invalid request", null);
                return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
            }

            $res = new TodoResponse(true, "Updated todo", $updated_todo);
            return response($res->to_json(), 201, ["Content-Type" => "application/json"]);
        } catch (\Exception $e) {
            $res = new TodoResponse(false, "Invalid request", $e->getMessage());
            return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
        }
    }

    public function delete($id)
    {
        try {
            $todo = Todo::query()->where('id', "=", $id);

            if (!count($todo->get())) {
                $res = new TodoResponse(false, "Invalid request", null);
                return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
            }

            $result = $todo->delete();

            if (!$result) {
                $res = new TodoResponse(false, "Invalid request", null);
                return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
            }

            $res = new TodoResponse(true, "Deleted todo", $todo);
            return response($res->to_json(), 200, ["Content-Type" => "application/json"]);
        } catch (\Exception $e) {
            $res = new TodoResponse(false, "Invalid request", $e->getMessage());
            return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
        }
    }
}

 

Step 8: Define the routes

Then, define the routes into the api.php file.

routes/api.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TodoController;
use App\Models\TodoResponse;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::get("/v1", function () {
    $res = new TodoResponse(true, "Message received", null);
    return response($res->to_json(), 200, ["Content-Type" => "application/json"]);
});

Route::get("/v1/todos", [TodoController::class, "index"])->name("todos.index");
Route::get("/v1/todos/{id}", [TodoController::class, "show"])->name("todos.show");
Route::post("/v1/todos", [TodoController::class, "store"])->name("todos.store");
Route::put("/v1/todos/{id}", [TodoController::class, "update"])->name("todos.update");
Route::delete("/v1/todos/{id}", [TodoController::class, "delete"])->name("todos.delete");

app/Exceptions/Handler.php

    public function register()
    {
        $this->renderable(function (NotFoundHttpException $e, $request) {
            if ($request->is('*')) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid route',
                    'payload' => null
                ], 404);
            }
        });
    }

The file will need to have the following import to work properly

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

This will be an exception handler to take care of any routes not specified in the routes file.

 

Step 9: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS