How to Create a Restful CRUD API in PHP Using Laravel and Google Firebase

January 13, 2022
Written by
Kenneth Ekandem
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

In this tutorial, you will learn how to create a RESTful CRUD (Create, Read, Update, and Delete) API with Laravel that stores its data in a Firebase realtime database.

What is Firebase?

Google Firebase is a Google-backed application development platform that enables developers to develop iOS, Android, and Web-based applications. Firebase provides tools for tracking analytics, reporting and fixing app crashes, creating marketing and product experiments, and much more.

So, without wasting time, let us dive in.

Prerequisites

  1. PHP 7.4, though ideally 8.1.
  2. Composer installed globally.
  3. jq.
  4. Prior experience with Laravel.
  5. A text editor such as Visual Studio Code or an IDE such as PhpStorm.
  6. A Google account.

Install and set up the Laravel application

To begin, you first have to install a Laravel application and run it on your local development machine.

To do that, in your terminal, run the command below.

composer create-project laravel/laravel laravel_firebase
cd laravel_firebase

These commands generate the new Laravel application in a directory named laravel_firebase, and then change it into that directory, so that all future commands are run from there.

Next, start the application by running the command below in your terminal.

php artisan serve

By default, Laravel projects bind to port 8000. So to view the running application, open http://127.0.0.1:8000/ in your browser of choice. It should look similar to the screenshot below.

The default Laravel home page

Once you see that the application is working, press ctrl+c to stop the application.

Set up a Firebase database

To access Firebase in Laravel, you will first have to configure Laravel to support it. This is done by installing a Firebase package for Laravel, such as kreait/firebase-php, which also supports Lumen projects.

To install the package, run the command below.

composer require kreait/laravel-firebase

Next, enable kreait/firebase-php's service provider by opening config/app.php and adding the following code in the providers element of the "Package Service Providers" section.

Kreait\Laravel\Firebase\ServiceProvider::class,

Connect to Firebase

Now that kreait/firebase-php's service provider is set up, we can create a new project in Firebase and connect it to our project, enabling us to add data to a database.

To accomplish that, we will complete the following steps:

  1. Create a new Firebase project.
  2. Create a service account.
  3. Get our project configurations and include them in our local Laravel project.
  4. Create a database.

Create project

To do that, go to your Google Firebase Console and click on the Add project button (which you can see below) which will bring up a dialog containing requirements to create a new project on Firebase.

Firebase Console add project

In step one of the "Create a project" wizard, enter a project name, click the checkbox next to "I accept the Firebase terms", and click Continue. In step two, uncheck "Enable Google Analytics for this project" and click Create project. A little while afterward, your project will be created. When it is, click Continue.

Create a Service Account

To get your service account configuration, go to Settings (at the top of the left-hand side navigation bar)  > Project settings and then select the Service accounts tab on the "Project settings" page.

Firebase Console add service account

When there, click on Generate new private key to download the JSON format of your service account key.

The JSON file gives whoever has it access to your Firebase project and data can be added and fetched, so be very careful where you store it and who can use it. Ideally, store the information in a password manager, such as 1Password or Bitwarden.

Add configurations

Now that we have our service account credentials downloaded, add it to the project's configuration. To do this:

  • Create a new directory in storage/app named firebase and move the JSON file there.
  • Add the following configuration setting to  .env., replacing the placeholder with the name of the JSON file. For simplicity's sake, I renamed my JSON file to laravel-firebase-fec.json.
// ...
FIREBASE_CREDENTIALS=/storage/app/firebase/<Your JSON filename.json>

Create a database

We have gotten and included our service project, now to another important aspect which is creating a database so we can add, edit, and read data.

To start, in the main navigation on the left-hand side of the window, under Build click Realtime Database. Then, click on Create Database and you will see a dialog with a dropdown option to choose the country your database should be located in.

Set the Firebase realtime database location

Select any one of the choices and click Next. Then, in the Security rules step, click Next.

When your database is done, click Rules and update the read/write permission to remain open for all time by changing the JSON to match the JSON below and click Publish.

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Next up, copy the configuration below to the bottom of .env.


// ...
FIREBASE_DATABASE_URL=<FIREBASE_URL>

Copy the Firebase database URL

Then, open the Data tab, copy your database URL (highlighted in the screenshot above), and then paste it in place of the placeholder in the configuration that you just added to the bottom of .env.

Then you can go ahead and publish the configuration for your Firebase service provider by running the below code on your terminal

php artisan vendor:publish --provider="Kreait\Laravel\Firebase\ServiceProvider" --tag=config

And that is it for setting up and using Firebase in our application.

Create a Firebase service

We will create a service class for Firebase that stores your credentials so we don’t have to repeat the process every time we want to make a request. To do that, in the app directory, create a new directory named Services. Then, in the Services directory, create a PHP file named FirebaseService.php.

Then, paste the following code into it.

<?php

namespace App\Services;

use Illuminate\Http\Request;
use Kreait\Firebase;
use Kreait\Firebase\Factory;

class FirebaseService
{
    public static function connect()
    {
        $firebase = (new Factory)
            ->withServiceAccount(base_path(env('FIREBASE_CREDENTIALS')))
            ->withDatabaseUri(env("FIREBASE_DATABASE_URL"));

        return $firebase->createDatabase();
    }
}

The above code will make use of the credentials which were stored in .env, earlier.

Create the core controller

Now that we are done with setting up Firebase for our application, we can create a controller to connect to Firebase and make CRUD requests against it. In your terminal, run the following command to create a new controller, named App/Http/Controllers/TestController.php.

php artisan make:controller TestController

Then, add the following snippet to the top of the class. It initialises a new class member variable, named $database, which provides the connection to the Firebase database.

private $database;

public function __construct()
{
    $this->database = \App\Services\FirebaseService::connect();
}

Add the ability to create records

Now, add the create function, below, to the controller. The function creates a new record in the Firebase database with the record data retrieved from the request parameters (title, and content).

public function create(Request $request) 
{
    $this->database
        ->getReference('test/blogs/' . $request['title'])
        ->set([
            'title' => $request['title'] ,
            'content' => $request['content']
        ]);

    return response()->json('blog has been created');
}

Add the ability to list all records

Next, add the code below after the create function.

public function index() 
{
    return response()->json($this->database->getReference('test/blogs')->getValue());
}

The function retrieves all records in the blogs table in the Firebase database, and returns them in a JSON response.

You can be more specific about the data you want to fetch as covered in the Kreait documentation.

Add the ability to edit records

Like most databases, Firebase gives us the ability to edit existing data sets within a database, which the connection, created by Kreait, makes quite trivial. To do that, paste the edit function, below, after the existing index function in TestController.php.

public function edit(Request $request) 
{
    $this->database->getReference('test/blogs/' . $request['title'])
        ->update([
            'content/' => $request['content']
        ]);

    return response()->json('blog has been edited');
}

The function retrieves a record from the blogs table in the database based on the title column. Then, using the returned object's  update function, it updates the record's content, using the content details supplied in the request.

Add the ability to delete records

Another core aspect of CRUD requests is the ability to delete records. To do that using Firebase and Laravel add the delete function, below, to TestController after the edit function. The function deletes all records whose title matches the value supplied in the title query parameter.

public function delete(Request $request)
{
    $this->database
        ->getReference('test/blogs/' . $request['title'])
        ->remove();

    return response()->json('blog has been deleted');
}

Add the required routes

Next, we add routes for the read, update, create, and edit data functions which we've just defined in TestController.php to the application's routing table. To do that, open routes/api.php and add the following code at the end of the file.

Route::post('/', [TestController::class, 'create']);
Route::get('/', [TestController::class, 'index']);
Route::put('/', [TestController::class, 'edit']);
Route::delete('/', [TestController::class, 'delete']);

Test the application

Now, it's time to test that the application works. To do that, we will be using Curl to test the individual endpoints we created to see the response and get the data it returns. Before we can do that, we need to start the application. To do that, run the command below.

php artisan serve

Create a blog post

To test if you can create a new blog post, run the curl command below from a new terminal window.

curl -d 'title=hello from me&content=This is from curl' http://localhost:8000/api/

On success, the command should return the response below.

"blog has been created"% 

Also, if you expand out the records in the database, you should see the new blog post details, similar to the screenshot below.

New record in a Firebase database

Update a blog post

Now, let's test updating a blog post. To do that, run the command below. Feel free to change the title and content values to something different, if you prefer.

curl -X PUT -d 'title=hello from me&content=This is from curl 2' http://localhost:8000/api/

After running the command, if you expand out the database records again in the Firebase Console, you should see that they've been updated, similar to the screenshot below.

Updated record in a Firebase database

Retrieve all blog posts

To test retrieving all posts, we will use curl again to call the API to retrieve all the available blog posts, piping the response to jq, so that it's easier to read.

To do that, run the command below.

curl -s  http://localhost:8000/api/ | jq

This will get all the posts added and returned as a JSON format in your terminal

{
     "hello from me": {
        "content": "This is from curl 2",
        "title": "hello from me"
    }
}

Delete a blog post

Then we'll finish up by testing the ability to delete a post, by running the command below.

curl -X DELETE -d 'title=hello from me' http://localhost:8000/api/

After the command completes, if you look at the database records again in the Firebase Console, you should see that they've been deleted, similar to the screenshot below.

Delete a record from a Firebase database

That's how to build a RESTful CRUD API in Laravel backed by Google Firebase

In the tutorial, you learned how to create a new Laravel application backed by Firebase using the Kieait package. The application was able to access a host of Firebase's amazing services, in particular a real-time database. If you want a full codebase, you can fork the Github repository and customise it to suit your needs.

Kenneth Ekandem is a full-stack developer from Nigeria currently in the blockchain space, but interested in learning everything computer science has to offer. He'd love to go to space one day and also own his own vlogging channel to teach the next generation of programmers.