Laravel is a PHP framework developed with PHP developer productivity in mind. The framework also aims to evolve with the web and has already incorporated several new features and ideas in the web development world, such as job queues, API authentication out of the box, real-time communication, and much more.

What are REST APIs?

A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer.

REST is a set of architectural constraints, not a protocol or a standard. API developers can implement REST in a variety of ways.

HTTP Verbs Represent Actions

  • GET: retrieve resources
  • POST: create resources
  • PUT: update resources
  • DELETE: delete resources

Setting Up a Laravel Web Service Project

Let's begin to create our fresh Laravel application for RESTful API.

composer create-project --prefer-dist laravel/laravel SimpleApi
//If you already installed laravel globel installer
laravel new SimpleApi

Database Configuration

Let's configure a database for our application. If you don't have a database then create a new one. After creating the database open .env file from the root directory of your project. if .env file is missing from the project then copy content from .env.example and create the file. .env file defines many common environment variables

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=**********
DB_USERNAME=*********
DB_PASSWORD=*********

Create Model and Migrations

Before creating model and migration let's understand what are model and migration.

What is a Model?

In Laravel, the Model is a class that represents the logical structure and relationship of the underlying database table. In Laravel, each of the database tables has a corresponding Model that allows us to interact with that table. Models give you a way to retrieve, insert, and update information into your data table. All of the Laravel Models are stored in the main app directory.

What is Migration?

Migrations are like version control for your database, allowing your team to define and share the application's database schema definition.

The Laravel Schema facade provides database-agnostic support for creating and manipulating tables across all of Laravel's supported database systems. Typically, migrations will use this facade to create and modify database tables and columns.

Let’s get started with our first model and migration - the Books. The book should have a title and an author field, as well as a publish date. Laravel provides several commands through Artisan - Laravel’s command line tool that helps us by generating files and putting them in the correct folders. To create the Books model, we can run:

php artisan make:model Books -m

This will create a Contact model and a migration file. In the terminal, we get an output similar to:

Model created successfully.
Created Migration: 2019_01_27_193840_create_books_table

Open the app/models/Books.php file and update it accordingly:

<?php

namespace App\Models;

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

class Books extends Model
{
    use HasFactory;
    protected $table = 'books';
    protected $fillable = ['name','author','publish_date'];
}

Open the database/migrations/xxxxxx_create_books_table migration file and update it accordingly:

<?php

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

class CreateBooksTable extends Migration
{
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('author');
            $table->date('publish_date');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('books');
    }
}

We added the name, author and publish date fields in the books table structure.

Migrating to Database

After defining our table structure, we have to create a table in the database using the below command :

php artisan migrate

Database Seeding

Database seeding is the process of filling up our database with dummy data that we can use to test it. Laravel comes with Faker, a great library for generating just the correct format of dummy data for us. So let’s create our first seeder:

php artisan make:seeder BooksSeeder

The seeders will be located in the /database/seeds directory. Here’s how it looks like after we set it up to create a few books data:

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Books;

class BooksSeeder extends Seeder
{
    public function run()
    {
        $faker = \Faker\Factory::create();
        for ($i = 0; $i < 50; $i++) {
            Books::create([
                'name' => $faker->sentence,
                'author' => $faker->name,
                'publish_date' => $faker->date,
            ]);
        }
    }
}

So let’s run the seed our database using this command:

php artisan make:seeder --class=BooksSeeder

Creating the Controller

Controllers are meant to group associated request-handling logic within a single class. In your Laravel project, they are stored in the app/Http/Controllers directory. The full form of MVC is Model View Controller, which acts as directing traffic among the Views and the Models. After creating the model and migrating our database. Let’s now create the controller for working with the Books model.

In your terminal, run the following command:

php artisan make:controller BookController

This command will generate a controller at app/Http/Controllers/BookController.php and update it accordingly :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Books;
class BookController extends Controller
{
    public function index()
    {
        $books = Books::all();
        return response()->json($books);
    }

    public function store(Request $request)
    {
        $book = new Books;
        $book->name = $request->name;
        $book->author = $request->author;
        $book->publish_date = $request->publish_date;
        $book->save();
        return response()->json([
            "message" => "Book Added."
        ], 201);
    }

    public function show($id)
    {
        $book = Books::find($id);
        if(!empty($book))
        {
            return response()->json($book);
        }
        else
        {
            return response()->json([
                "message" => "Book not found"
            ], 404);
        }
    }

    public function update(Request $request, $id)
    {
        if (Books::where('id', $id)->exists()) {
            $book = Books::find($id);
            $book->name = is_null($request->name) ? $book->name : $request->name;
            $book->author = is_null($request->author) ? $book->author : $request->author;
            $book->publish_date = is_null($request->publish_date) ? $book->publish_date : $request->publish_date;
            $book->save();
            return response()->json([
                "message" => "Book Updated."
            ], 404);
        }else{
            return response()->json([
                "message" => "Book Not Found."
            ], 404);
        }
    }

    public function destroy($id)
    {
        if(Books::where('id', $id)->exists()) {
            $book = Books::find($id);
            $book->delete();

            return response()->json([
              "message" => "records deleted."
            ], 202);
        } else {
            return response()->json([
              "message" => "book not found."
            ], 404);
        }
    }
}

Creating The Routes

Route is a way of creating a request URL for your application. These URLs do not have to map to specific files on a website. The best thing about these URLs is that they are both human-readable and SEO-friendly.

We have already created a method to handle CRUD for the books table. Now we need to provide implementations for these methods at specific URLs. For that, we have to create routes for particular functions. In Laravel, All API routes must be added to a particular file routes/api.php.although you can create a custom route file and bind it to your application.

In this example, we are going to use the default route file so Open the routes/api.php file and update it accordingly

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;


Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
Route::get('/books',[BookController::class, 'index']);
Route::get('/books/{id}',[BookController::class, 'show']);
Route::post('/books',[BookController::class, 'store']);
Route::put('/books/{id}',[BookController::class, 'update']);
Route::delete('/books/{id}',[BookController::class, 'destroy']);

This route binds functions to a specific URL which is listed below:

  1. GET /books, mapped to the index() method
  2. GET /books/{id}, mapped to the show() method
  3. POST /books, mapped to the store() method
  4. PUT /books/{id}, mapped to the update() method
  5. DELETE /books/{id}, mapped to the destroy() method

Running Laravel API Application

For Running or Testing API applications enter the below command :

php artisan serve

It will produce output like the below :

Starting Laravel development server: http://127.0.0.1:8000
PHP 7.4.6 Development Server (http://127.0.0.1:8000) started

Now we can test our API endpoints using any API testing tool.