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

PHP has been the most popular web language in the present times by being simple to maintain, and quick to create feature-rich web applications. Websites that are dynamic, interactive, secure and efficient, need a powerful tool set to create and consume APIs.

An efficient API is needed in our times in order to develop content that boosts discoverability and help achieve business goals, PHP is the language that most web developers use and software that has recently been the most successful on deploying web applications.

If you are using PHP you probably already know how useful RESTful APIs can be. You can brush up on API concepts.

Now let’s look at building a PHP RESTful API with Laravel.


Let’s look at these technologies as we build our API:

  • PHP
  • Composer
  • Laravel
  • Docker

PHP will be our language of choice in developing our API. There are many ways we can install PHP on our system, although we will be using Docker to run our services.

Composer is a package manager for PHP. You can declare the dependencies your application depends on and it will download them for you to use. Let’s download and install Composer.


Follow this link to download:

Follow this link to Install:

Now we can install Laravel by running the Composer command:

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

By running this command Composer will download and install Laravel and any needed dependencies, creating a project for us to start working. You can read the full installation quick start here:

Once everything has been downloaded you can test out the installation by running:

php artisan serve --port=8080


Docker is very useful for running our services in a containerized environment. It will install all the needed software so we can focus on coding. A Docker container will provide a place for us to run our API and test locally on our computer. For instructions on how to install Docker for mac follow this link:

There are also ways to install for Windows and Linux.

Once Docker has been installed we can begin to create our PHP service.

We will begin by creating a “Dockerfile”. This will define what we want to create a PHP service, install Composer and create our Laravel project.

# Use this docker container to build from
FROM php:7.0.28-apache

# 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 

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

# set our application folder as an environment variable
ENV APP_HOME /var/www/html

# change uid and gid of apache to docker user uid/gid
RUN usermod -u 1000 www-data && groupmod -g 1000 www-data

# enable apache module rewrite
RUN a2enmod rewrite
RUN a2enmod ssl
RUN a2enmod headers

# apache configs + 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

# mod_rewrite for URL rewrite and mod_headers for .htaccess extra headers like Access-Control-Allow-Origin-
RUN a2enmod rewrite headers

# copy source files and run composer

# install all PHP dependencies
RUN composer install --no-interaction

# change ownership of our applications
RUN chown -R www-data:www-data $APP_HOME

Now that we have our Dockerfile, we can define our docker-compose.yml file. This will define our Laravel API and a MySQL database we can easily use to store data.

version: "3"

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

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


This docker-compose.yml file creates two services for us.

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

This also references a .env file, which is an environment file.

Let’s create a .env file to store our environment variables.







Docker Compose

Now we can bring up our services locally to view our Laravel API. Let’s start with some docker-compose commands.

docker-compose up

If there were no errors you should be able to go to http://localhost:8080 and see the Laravel home screen.

laravel home

Planning the API

We will plan our service to use best practices so we can maintain and build feature-rich APIs. The URL is just an example. You will likely change this to your own domain.

First, let’s define our photo API:

  • GET
    • – This will get the photo with an id of 1
  • POST
    • – This will create the photo
  • PUT
    • – This will update the photo with an id of 1
    • – This will delete the photo with an id of 1

Each photo will contain:

  • id of the photo
  • URL
  • name
  • created date
  • updated date

With Laravel, we can define a resource controller, that will make it easy for us to create this API.

Docker is very useful to be able to isolate a certain environment. Let’s login to the docker container and run Laravel commands, that will create features of our API:

# This will log us into the docker container which will enable us to run Laravel commands
docker-compose run --rm laravel /bin/bash

# This will create a photos table for us
php artisan migrate:make create_photos_table

The first docker-compose run command will log us into the container so we can run Laravel commands.

The second command will create a database migrate for us called Photos. Under app/database/migrations you can see your newly created migration. A migration will run PHP code and create a MySQL table. By doing this we can store our photos in our database and have them served up in Laravel.

Let’s add to our migration so we can store a photo URL and name:


use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreatePhotosTable extends Migration {

   * Run the migrations.
   * @return void
  public function up()
    Schema::create('photos', function($table)

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


Now we can run this command to run the migration:

php artisan migrate

Laravel Controller

Now we have our database running we can create a Laravel Controller that will define all our endpoints.

First, we need to create the controller:

php artisan controller:make PhotoController

Now we need to add our routes to the app/routes.php file:

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

Finally, we can define our PhotoController:


class PhotoController extends BaseController {
  // We will define our API endpoints here.

And we also need to create a file models/Photo.php

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('');

Let’s add these methods to our PhotoController class.

Getting a list of Photos

The first endpoint we will define is our index. By calling this we can 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

This will find the photo record in the database from the id. Then we can update from the user input of URL and name. It will then save the record in the database and return the JSON object back to the client.

   * 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

This will remove the photo from the database by calling the endpoint with the photo id.

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

By using a Laravel resource controller we can easily and powerful set up a RESTful API.

Testing the Laravel API

Laravel will give us a powerfully simple API that we can consume. If you have your Docker container running we can test out the API.

Let’s use Postman to test our API calls:

Once you have deployed your application you can start using RapidAPI.

Click here to add your API and get started with RapidAPI.


In this article, we learned how to install Composer, Laravel, Docker, and how we can leverage containers to create our Laravel API.

We used Docker Compose to create a Laravel application and MySQL service, we can now save our data to a database and have it persist.

We created Photo Controller that lets us build powerful yet simple APIs in Laravel.

Finally, we tested out our API with Postman to see how the data structure can be consumed.

Related Resources


The post How to Build a RESTful API in PHP (with Laravel) appeared first on Last Call – RapidAPI Blog.

Source: RapidAPI