Creating PHP API with Laravel and PostgreSQL

Ronaldo B.July 27, 20229 min read

In this article

In this article, we will create an API using Laravel in connection with PostgreSQL.

If you do not have Laravel, you can see how to install it by accessing our article Installing and Configuring Laravel on Windows, Linux and Mac.

In one of our latest articles, we taught how to install Postgres and also created a first table. You can access this content by clicking here.

It will be based on this Database that we will create our API.

Starting the API

To start a project in Laravel, we will use the following command: laravel new hcode-api-users.

After creating our application, we will access it in the Terminal with the command cd hcode-api-users and configure the Database. To do this, we will edit the .env file at the root of our project, providing the credentials for our Database. It will look like this:

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=hcodedb
DB_USERNAME=postgres
DB_PASSWORD=root

In addition, since we will be connecting to Postgres, we need to check if our PHP has the DLLs for this Database defined in our configuration file. If you are using XAMPP, you can check this configuration in the file xampp/php/php.ini. The following two lines should be uncommented:

extension=pdo_pgsql
extension=pgsql

Now that all the initial configuration is done, let's start the API server. To do this, we will run the command php artisan serve in our Terminal. The following message will be returned in the Terminal:

Message returned in our Terminal after starting the server

Creating the first route

The first route we will create will be the route to list users. The routes file in Laravel is located in the routes folder. We will edit the api.php file. This file makes use of the Route class. It has a static method for each HTTP request method. To list users, we use the GET method. Thus, we will add the following code to our file:

Route::get('users', function() {
	return 'Working!!!';
});

Explaining: the first parameter for the method is the route itself, that is, “users”. The second parameter is a function that will be executed when accessing the route. In this case, we will simply return a string.

To test this route, we need to access the URL localhost:8000/api/users in our browser. Note that we specified “/api”, which is the name of our PHP file. When accessing this address in the browser, we see the following result:

Result of our “users” route in the browser

Excellent, our route worked. Very simple, don’t you think?

The next step is to make this route dynamic. After all, we want to list the users from the Database, not just return a static message. This leads us to the next resource of Laravel.

Listing Users

Laravel uses the MVC (Model View Controller) pattern. According to this pattern, instead of leaving the business logic explicit in the routes of our application, we should include it in a specific class, our Controllers. It will be through them that we will return the users to our route.

We can create a Controller via the command line, using php artisan, followed by the name of the Controller we are creating. We will execute the following command:

php artisan make:controller UsersController

Our Controller will be automatically created in the app/Http/Controllers folder. It is recommended to always create Controllers in the plural form. This is considered a good practice.

Our Controller has been created successfully. However, it is not responsible for going to the Database and retrieving the data. This function is performed by the Model, another layer of the MVC structure. We can say that the controller is the one that acts as the “middleman” to bring the data to the route. But who will fetch this data is the Model.

To create a Model, we can again use the resources of php artisan. We will execute the following command:

php artisan make:model User

Note that the Model is created in the singular form, and this is also considered a good practice. When we execute this command, an error will be returned, indicating that this Model already exists. This occurs because the Model named “User” is one of those that Laravel provides us by default. However, if we need to create other Models, we can use the same command.

Now that both the Controller and the Model have been created, let's connect one to the other. We will do this in the UsersController.php file. We will create a method called index(), which will be what we inform in the routes file.

This method will call the all() method, which comes from the User Model. This method aims to retrieve all records from the users table. Our code will look like this:

use App\User;

public function index() {
	return User::all();
}

Now let’s call this method in our api.php file. It will look like this:

Route::get('users', "UsersController@index");

Explaining: we replaced the function we were executing before with the call to the UsersController class and the index method, which were separated by the at symbol (@).

Now, when accessing the same address in the browser, we see the following result:

Users rendered in the browser

Our users are being listed through our API. But note that at no point did we execute a SELECT command with PHP, in an imperative way. We only need to create methods in our classes, in a declarative manner, and Laravel brought us the desired data. Incredible, isn’t it?

Creating a User

Now we will program the creation of a user through our API. We will start by creating the method in our Controller. We will name it store(). It will have the following code:

public function store(Request $request) {

	$user = User::create([
		"name"=>$request->input("name"),
		"email"=>$request->input("email")
	]);

	return $user;

}

Explaining: this method expects the request from our client as a parameter, which in Laravel is represented by the Request class. This class will contain all the posted information, such as the name and the email of the new user.

Again, we use the User Model and call its create() method, another native resource of Laravel, which is responsible for creating the new record in the Database. We provide this method with an array of the data we want to insert. Note that we use the input() method of the Request class. This method is responsible for actually identifying the value of what was posted by the user.

Now let’s call this method through our routes file. We will do this with the following line of code:

Route::post('users', "UsersController@store");

Note that once again we used the “users” route. However, now with the post() method.

To test this route, we can use Insomnia, a very powerful REST Client. We taught how to install it and showed some of its resources in the article Using Insomnia to Test Our APIs Requests.

Let’s access it and create a new request:

Option to create a new request in Insomnia

Let's name this request “Hcode API POST”:

Creating the new POST request

Let's make it clear that this is a POST request and set the request body type to “Form URL Encoded”:

Defining the type of POST request body

We now need to provide the fields we will post and the value of each of them:

Informing fields that will be sent to the API

The next step is to define the URL we will access:

Defining the URL we will access

Finally, just click on “Send”. When we do this, we see the following error in Insomnia:

Error returned in Insomnia

This error occurs because Laravel requires that we have two standard columns in all tables we create. These columns are “updated_at” and “created_at”. They are constantly updated by Laravel.

Therefore, let's access our Postgres and add these columns to the users table. We will execute the following command:

ALTER TABLE users
	ADD COLUMN updated_at TIMESTAMP DEFAULT NULL,
	ADD COLUMN created_at TIMESTAMP DEFAULT NULL;

Now, when we send the request again, we see the following result:

Inserted data being returned in Insomnia

Perfect! Our data has been inserted correctly.

Editing a User

To edit a user, we will create a method in our Controller called update(). It will expect as parameters the data provided by the request, but also the information of the already existing user we want to change. Its structure will be as follows:

public function update(Request $request, User $user) {

	$user->name = $request->input('name');
	$user->email = $request->input('email');

	$user->save();

	return $user;

}

Explaining: the values of the “name” and “email” properties of the User Model will be replaced by the information posted by the user. However, for this to be possible, it is necessary that we explicitly state in our Model that these properties can be edited. For this, we use a property called $fillable, which translates to “fillable”.

The User Model, created by default by Laravel, already has this property, which by coincidence already contains the attributes “name” and “email” defined. Thus, we do not need to worry about this configuration:

Property $fillable in the User Model

The method in our Controller is ready. Let's call it in our routes file. To edit a user's data, we can choose between using the PUT or PATCH methods. The first aims to edit all data of a specific user. The second edits only part of our user data and will be the one we choose. Our file will look like this:

Route::patch('users/{user}', "UsersController@update");

Note that we specified the word “user” in braces for the route. This constitutes a parameter for our edit route. This parameter will be the ID of the user we want to edit. Laravel itself will load its information and edit it.

Let's create a new request in Insomnia, called “Hcode API PATCH”:

Creating edit request in Insomnia

Let's inform our API's URL for this request, defining ID 3 as the one that will be edited, along with the information we want to update:

Informing edit data for our API request

When we click “Send”, we see the following result:

Result of our edit request

Our data has been updated successfully!

Deleting a User

Finally, let's program the deletion of a user. We will create a method called remove() in our Controller. It will expect as a parameter only the data of the user we are going to delete, which will be represented by the User Model. Then, we will call the delete() method that this class has. Its code will be as follows:

public function remove(User $user) {

	$user->delete();

	return response()->json([
		'message'=>'User deleted successfully'
	]);

}

Let's call this method in our routes file, using the delete() method:

Route::delete('users/{user}', "UsersController@remove");

Note that in this case we also used parameter passing for the route.

Let's create the delete request in Insomnia named “Hcode API DELETE”:

Creating delete request

Let's define the API URL in our request, informing ID 1 for it.

Informing the URL for deletion in our API

We will see the following result when we send it:

Success message in deleting the user

Our user has been successfully deleted.

It is interesting to note that we built a user CRUD without almost accessing the Database. Laravel did that for us. Thus, if we wanted to manipulate another Database that was not Postgres, we would only need to change the access configurations to it that we defined in the .env file, and the code would continue to work.

You can find the codes developed in this article on our GitHub.

Laravel is truly a “handy tool” for creating APIs in PHP in a much faster and simpler way. We teach other resources of this amazing framework in our course Creating REST API with Laravel 5.7.

Thank you for reading and see you in the next article :)

Keep learning with Hcode

Sign up for the course platform and follow the next blog guides.