Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Create Rest APIs in Laravel

How to Create Rest APIs in Laravel ?

Aman Jain, July 4, 2022August 2, 2022

Rest APIs are used to create the communication between client and server and in this application we will learn to create rest apis in laravel. Rest API is a architectural style which same as both server and client end so any client can consume the apis since it has industry standard format. Using rest apis we can send request to store client data and can request for any type of data from server.

Rest api is lightweight and most reliable method to connect multiple serve and clients. There can be 5 types of request we can send in rest apis as follow

  1. GET
  2. POST
  3. DELETE
  4. PUT

So GET is used to fetch the records and send simple information in query param. POST mostly used to submit the data and create new records, DELETE is used to delete records and PUT is used to update the existing records in application.

In this tutorial we will create all method routes and will implement the basic crud operations. If you want to learn authentication in Rest APIs then you can read How to Implement JWT Auth in Laravel? article.

let’s start the tutorial of Create Rest APIs in Laravel step by step

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

composer create-project laravel/laravel blog

You can also read this to start with new project

Step 2 : Database Connection

I assume the you have already installed the laravel and basic connection of it like database connection and composer.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-jwt
DB_USERNAME=root
DB_PASSWORD=

Step 3 : Create Model and Migrations

Now, for basic example to retrieve, add , edit and delete i am creating a article model so that we can easily perform basic CRUD operation in rest api

php artisan make:model Article -m

this will generate the model and migration file

<?php

namespace App\Models;

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

class Article extends Model
{
    use HasFactory;
    
}

and migration file database/migrations/timestamp_create_articles_table.php

 
     public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();;
            $table->string('title');
            $table->string('body')->nullable();
            $table->string('image');
            $table->timestamps();
        });
    }

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

and then migrate the migration

php artisan migrate

Step 4 : Create controller

Next, Create a resource controller which by default add the necessary methods for Add, Update, Edit and Delete.

this is not mandatory to create resource controller you can also create custom methods according to your requirements.

php artisan make:controller ArticleController

and add the below code

<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
      
            return Article::all();   
         //   return response()->json(["status"=>true, "message"=>"success","data"=>Article::all()]); //or cusom json
    }
 
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validations=[
            'title' => "required",
            'email' => "required|email|unique:articles,email",
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
        ];

        $validator = Validator::make($request->all(), $validations);

        if ($validator->fails()) {
            return response()->json($validator->errors(),422);
        }
        //  save image and name in database
        
        $Article = new Article();
         
        $Article->title = $request->title;
        $Article->email = $request->email;
        if($request->hasFile("image")){
            $file = $request->file("image")->store("uploads/images");
            $Article->image = $file;
        }
       
        $Article->body  = $request->body;
        $Article->save();
        return response()->json(["status" => true,"data"=>$Article, "message" => "You have successfully created the article."]);
        
    }

  
    public function update(Request $request, $id)
    {
        $validations=[
            'title' => "required",
            'email' => "required|email|unique:articles,email,".$id,
           
        ];

        $validator = Validator::make($request->all(), $validations);

        if ($validator->fails()) {
            return response()->json($validator->errors(),422);
        }
        //  save image and name in database
        
        $Article = Article::find($id);
         
        $Article->title = $request->title;
        $Article->email = $request->email;
        if($request->hasFile("image")){
            $file = $request->file("image")->store("uploads/images");
            $Article->image = $file;
        }
       
        $Article->body  = $request->body;
        $Article->save();
        return response()->json(["status" => true,"data"=>$Article, "message" => "You have successfully updated the article."]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Article::find($id)->delete();
        return response()->json(["status" => true, "message" => "Record deleted successfully"]);
        
    }
}

Here in above code we have used four methods

Function index : To show all articles.

Function store : To create new article.

Function update : To update the article.

Function destroy : To delete the article.

Note: in a PUT request we can pass additional key _method=PUT and can send a post request to submit form.

Step 4: Create routes in routes/api.php

Create resource route or route for each api as follow

routes/api.php

<?php

use Illuminate\Support\Facades\Route;
 
Route::resource('articles', '\App\Http\Controllers\ArticleApiController');

//or

//Route::get('articles', '\App\Http\Controllers\ArticleApiController@index');
//Route::post('articles', '\App\Http\Controllers\ArticleApiController@create');
//Route::delete('articles/{id}', '\App\Http\Controllers\ArticleApiController@destroy');
//Route::put('articles/{id}', '\App\Http\Controllers\ArticleApiController@update');

Screenshot:

Laravel Rest Create API tutorial
Laravel Rest API tutorial
Screenshot 2022 07 04 at 8.38.18 AM
Laravel Rest API tutorial
Screenshot 2022 07 04 at 8.41.10 AM
Laravel Rest API tutorial
Screenshot 2022 07 04 at 8.41.23 AM
Laravel Rest API tutorial

Related

Php Laravel Laravel 9 deletegetlaravelrest api

Post navigation

Previous post
Next post

Related Posts

Php Ajax Image Upload with form in Laravel 8 9 with example

Ajax Image Upload with form in Laravel 8 / 9 with example

June 3, 2022June 4, 2022

Ajax image Upload with preview in laravel 9 can be implement easily using the laravel file and storage providers.In a website Image uploading can be used in multiple places like set up a profile picture to providing the documents. Laravel 9 provides robust functionality to upload and process the image…

Read More
Php laravel routing

Laravel 8 routing with example

October 5, 2021January 13, 2022

In this post we will learn to implement the Laravel 8 routing and how it’s different from Laravel other versions. Laravel routing is used to create the URL for each POST, GET requests and it works as a bridge between the controller or html view. In this article we will…

Read More
Php How to Create or Replace File Content in Laravel

How to Create or Replace File Content in Laravel ?

May 29, 2022November 9, 2023

This article will guide you to Check File exist and Create or Replace File Content in Laravel. To perform the file system based operations like Check file exist and create or replace file in laravel. we use File class or Storage class in laravel. Laravel provides inbuilt library to access…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version