Laravel is used to build various server-side applications in the industry. Using Laravel to build APIs is a quite popular these days since it’s fairly easy with Laravel. It comes with Migrations, Pre-defined validations, Easy to manage MVC architecture and so on. And today we’re gonna learn how to build a REST API in Laravel with CRUD functionality

In this tutorial we’re building a Simple REST API with CRUD (Create, Read, Update, Delete) functionality using Laravel. We’ll be creating an API that manages Products. So, the API will be able to Create, Read, Update and Delete products in the database.

Getting Started – REST API in Laravel with CRUD

First thing’s first! Let’s get started by Installing and Setting Up Laravel.

Once the installation is complete, edit the .env file with correct details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=crud_api
DB_USERNAME=root
DB_PASSWORD=

Create Migrations

Next Let’s create a Migration that create a table to store the products. Go to the terminal and hit the following command to create the migration.

php artisan make:migration create_products_table

Open up that migration file and define the table.

 
class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('description');
            $table->float('price');
            $table->string('tags');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Great! Now run that migration with the following command to acctually create the table.

php artisan:migrate

OK, next step to create a model for the table and a controller to create all the methods that do the functionality. Let’s do that real quick.

Model and the Controller

To create the model:

php artisan make:model Product

Laravel has a special system that matches the naming conventions and automatically maps the table to the model. So, if the table name is “items”, name the model “Item”. If you follow this naming convention pattern, you don’t need to define the table name in the model.

OK, now create the controller as well:

php artisan make:controller ProductController --resource

The reason, I used –resource keyword at the end of command is that it create all the CRUD methods automatically. These are called resource controllers.

One final step before start coding. Creating routes.

Define Routes

Routes are the URLs that we can access the methods in the controller.

Open up the routes folder and open api.php file. Add this line of code.

Route::resource('/products', 'ProductController');

This is a Resource route. This contains all the routes needed for a CRUD. Which is POST, GET, PATCH, DELETE.

Great! Now we got everything in place to develop the application logic for the API.

Develop the API

Before start writing any code, I recommend you to download and install Postman for testing the API. We use postman to call all the endpoints of the API.

Alright, let’s get into coding.

store() 

Open the ProductController.php and let’s start editing store() method.

public function store(Request $request)
    {
        $product = new Product();
        $product->title = $request->title;
        $product->description = $request->description;
        $product->price = $request->price;
        $product->tags = $request->tags;
        $product->save();

        return response()->json(['status' => 'Success', 'message' => 'Product Saved']);
    }

First we create an object of the Product model and then assign values to it’s parameters.

Now. let’s test this on Postman. Open up a new tab and type URL as follows.

https://{YOUR_LOCAL_HOST}/api_laravel/public/api/products

REST API in Laravel with CRUD  - Type URL in Postman

Now Change the request method to POST. Great! Next add the JSON body as a raw.

Now everything is set and hit send button. If everything was followed correctly, you should get this response.

REST API in Laravel with CRUD  - Response

Cool, isn’t it?

Now you can add products using the API.

update() 

Alright, now same way, we can create the UPDATE method as well. Add the following code to your update() method.

public function update(Request $request, $id)
    {
        $product = Product::find($id);
        $product->title = $request->title;
        $product->description = $request->description;
        $product->price = $request->price;
        $product->tags = $request->tags;
        $product->save();

        return response()->json(['status' => 'Success', 'message' => 'Product Updated']);
    }

Here we don’t create a new record. We find the particular row with the ID of the product and then we update it.

Again, open up Postman and add the URL as follows.

https://{YOUR_LOCAL_HOST}/api_laravel/public/api/products/{ID}

And change the request method to PATCH. Add the JSON body same as we added earlier. And hit enter. You’ll get the following response if no errors.

REST API in Laravel with CRUD  - Response

Now we implemented CREATE and UPDATE products. Now it’s time to implement GET ALL PRODUCTS and GET SINGLE PRODUCT endpoints.

index()

Here we write code to get all the saved product.

public function index()
    {
        $products = Product::all();
        return response()->json(['status' => 'Success', 'data' => $products]);
    }

This is a GET request. So, change the Request type to GET.

https://{YOUR_LOCAL_HOST}/api_laravel/public/api/products

And we don’t add request body for this request.

You’ll get this, as the response.

REST API in Laravel with CRUD  - all Products - Postman

show()

Same way add the code for viewing a Single product.

public function show($id)
    {
        $product = Product::find($id);
        return response()->json(['status' => 'Success', 'data' => $product]);
    }

This is also a GET request.

https://{YOUR_LOCAL_HOST}/api_laravel/public/api/products/{ID}

You’ll get this, as the response

REST API in Laravel with CRUD  - Single Product -- Postman

 

destroy()

Alright! Now let’s write the final method of this API. Which is DELETE.

public function destroy($id)
    {
        $product = Product::find($id);
        $product->delete();
        return response()->json(['status' => 'Success', 'Message' => 'Product Deleted']);
    }

This is a DELETE method. Change the request method to DELETE and add the URL as follows.

https://{YOUR_LOCAL_HOST}/api_laravel/public/api/products/{ID}

You’ll get this response.

REST API in Laravel with CRUD  - delete product postman

Great! Now our API is pretty much complete. We created an almost complete REST API in Laravel with CRUD functionality. Using this API,  You can CREATE, READ, UPDATE and DELETE items.

This is just a starting point. In our next tutorials, we’re gonna discuss how to improve this API to match more practical scenarios such as Validations, Authentication and File handling and so much more.

Will see ya!

Download Project files for this tutorial