Back to blog

How to Build a RESTful API in PHP (with Laravel)

APIAPI integrationapp developmentPHP 7php developmentRESTful API

Complimentary Consultation

We will help you to optimize your tech debts and the user journey of your product


PHP has long been one of the most popular programming languages ​​, as it makes it easy to maintain and build a rich web application. Most of the interactive and dynamic websites we see today need a set of tools to create and consume APIs.

Today, a useful API helps in content development and improves user experience and helps achieve business goals. This language is used by many developers and the software that has recently been the most successful in deploying web applications.

If you’ve ever experienced software development before, you will probably be familiar with RESTful APIs and how useful they can be. For more details, we suggest that you familiarize yourself with our article.

Let’s overview of the process of building a PHP RESTful API with Laravel.


Here are technologies that we use to build API:

  • PHP. We have chosen PHP as the programming language for API development. There are several ways to work with PHP, but we’ll use Docker to run our services.
  • Composer. It is an application-level package manager for the PHP programming language that allows you to declare the libraries your project depends on and manage (install/update) them for you.
  • Laravel
  • Docker

Let’s download and install Composer. 


Since the Composer installation is completed, we can install Laravel by running the first one command:

composer create-project laravel/laravel your-project-name 4.2.0

After this command, the Composer should download and install Laravel and the necessary dependencies, creating a project with which we will work in the future. You can read more about the installation here.

Once downloading and installing are finished, you can test the installation using the following command:

php artisan serve --port=8080


Docker is used to running services in a containerized environment. It takes over the functions of installing the necessary software so that you can focus on coding. The Docker container is useful for running APIs and testing locally on your machine. You can find out how to install Docker on your computer here.

Docker containers are present throughout the software development cycle, and their primary use is in deployment.

Since the Docker installation is complete, you can start building the PHP service.

The first place to start is creating a “Dockerfile.” Our actions will be as follows:
step #1  is to point which the docker container to build from

FROM php:7.0.28-apache

step #2 To install all the system dependencies and enable PHP modules

RUN apt-get update && apt-get install -y
 && rm -r /var/lib/apt/lists/*
 && docker-php-ext-configure pdo_mysql --with-pdo-mysql=mysqlnd
 && docker-php-ext-install

step #3 To install composer

RUN curl -sS | php -- --install-dir=/usr/bin/ --filename=composer

step #4 To set our application folder as an environment variable

ENV APP_HOME /var/www/html

step #5 Change uid and gid of apache to docker user uid/gid

RUN usermod -u 1000 www-data && groupmod -g 1000 www-data

step #6 Enable apache module rewrite

RUN a2enmod rewrite
RUN a2enmod ssl
RUN a2enmod headers

step #7 Set up apache configs and document root

ENV APACHE_DOCUMENT_ROOT=/var/www/html/public
RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf

step #8 Define the command: mod_rewrite for URL rewrite and mod_headers for .htaccess extra headers like Access-Control-Allow-Origin-

RUN a2enmod rewrite headers

step #9 Now we need to copy source files and run composer


step #10 Install all PHP dependencies

RUN composer install --no-interaction

step #11 Change ownership of our applications

RUN chown -R www-data:www-data $APP_HOME

We can configure our application services in a docker-compose.yml file and define the API and a database.

version: "3"

    build: .
      - "8080:80"
      - .env
      - .:/var/www/html:cached
      - laravel-db

    image: mysql:5.6
      - "3306:3306"
      - .env
      - laravel-db:/var/lib/mysql


The docker-compose.yml file provides two services.

  • laravel – This will define our PHP Laravel service. It will contain a volume of our code, and ports to access an API through the browser.
  • laravel-db – This will define the MySQL service to store our data.

It references a .env file, which is used as an environment. Now we are going to create a .env file to store our environment variables.







Docker Compose

Now it is possible to call the services locally for viewing API. Here are some docker-compose commands.

docker-compose up

If we made everything right, there would be possible to go to https://localhost:8080, where the Laravel home page will be shown.

Planning the API

We want to create feature-rich APIs to make our services demand.
Let’s take an example with the URL, but you can name your domain whatever you want.
Our first step will be to define photo API:

GET – to get the photo with an id 1
POST – to create the photo
PUT – to update the photo with an id 1
DELETE – to delete it

Every picture should have:

  • id
  • URL
  • name
  • created date
  • updated date

Laravel usage will allow us to define a resource controller.

A tool like Docker allows you to isolate a specific environment. And now, through the docker container, using Laravel commands, let’s create API functions:

docker-compose run --rm laravel /bin/bash

Then create a photos table with the command

php artisan migrate:make create_photos_table

With the second command, we made a database migration called Photos
Check the app / database / migrations section. During the migration, the PHP code will also run, and the database table will be created. Thus, our photos will be stored in the database and, if necessary, transferred to Laravel.

Now we need to add a photo URL and name to the migration.

<?php use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; class CreatePhotosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('photos', function($table) { $table->increments('id');

   * Reverse the migrations.
   * @return void
  public function down()


To start the migration we will use the next command.

php artisan migrate

Laravel Controller

Let’s create a Laravel Controller to define all endpoints.

php artisan controller:make PhotoController

After this we have to add our routes to the app/routes.php file:

Route::resource('photo', 'PhotoController');

It’s time to define our PhotoController:

class Photo extends Eloquent {

 * The database table used by the model.
 * @var string
 protected $table = 'photos';

 * The attributes excluded from the model's JSON form.
 * @var array
 protected $hidden = array('');

Make sure you add these techniques methods to the PhotoController class.

Getting a list of Photos

In the beginning, we need to define the index by doing this we get a list of photos.

   * Display all photos.
   * @return Response
  public function index()
    $photos = Photo::all();
    return $photos;

Creating a photo

This will store our photo in the database and return in JSON our newly created id and photo record. We get user input by calling the Input::get method.

   * Store a newly created photo.
   * @return Response
  public function store()
    $photo = new Photo;
    $photo->url = Input::get('url');;
    $photo->name = Input::get('name');;
    return $photo;

Updating a photo

Using the ID, we can find the photo in the database. Next, if necessary, change the URL and name entered by the user, and the record will be saved and returned to the user as a JSON object.

   * Update the photo.
   * @param  int  $id
   * @return Response
  public function update($id)
    $photo = Photo::find($id);
    $photo->url = Input::get('url');;
    $photo->name = Input::get('name');;
    return $photo;

Deleting a photo

Using the ID also we can remove a photo from the database.

   * Remove the photo
   * @param  int  $id
   * @return Response
  public function destroy($id)
    $photo = Photo::find($id);


In this article, we learned how to install Composer, Laravel, Docker, and use containers to build our Laravel API. To create a Laravel application and databases, we used Docker Compose, which gives us the ability to store data in the database. And also, the Photo Controller was created, which allows you to create APIs in Laravel.

Use the Laravel Passport, it has a mechanism to generate access tokens to work with API
You should use Laravel Resources:
Laravel supports ::paginate - method for all the records so you can simple output Photo::paginate(20) to get paginated list
Sign up for the latest Altamira news
Latest Articles

Looking forward to your message!

  • Our experts will get back to you within 24h for free consultation.
  • All information provided is kept confidential and under NDA.