Create Laravel CRUD REST API

In this post we will learn how to create CRUD (Create, Read, Update and Delete) Rest API in Laravel and run with Postman

First we have to create a new Laravel application using below composer command

composer create-project --prefer-dist laravel/laravel backendAPI

Get in your application

cd backendApp

Now create database and configure it using .env file (.env file you can find or create inside root directory)

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

Create Controller: Create a controller for CRUD functions (index, Update, show and destroy) using php artisan command we can create a cotroller in Laravel using the “—resource” it will create all basic crud functions

php artisan make:controller UserController –-resource

Create Routes: now open api.php and create api routes “routes/api.php”

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\http\controllers\UserController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::resource('users',UserController::class);

Migrate Database : Migrate database using php artisan command “php artisan migrate”

php artisan migrate

Store Function : Create Post API for store or Save data using usercontroller.

 app\Http\Controllers\UserController.php

public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:50',
            'email' => 'required',
            'password' => 'required'
          ]);
      
          $user = new user([
            'name' => $request->get('name'),
            'email' => $request->get('email'),
            'password' => $request->get('password'),
          ]);
      
          $user->save();
      
          return response()->json($user);
    }

Run Post API using postman

Index Function : Create Get API for fetch all records to database using usercontroller.  app\Http\Controllers\UserController.php

public function index()
    {
        $user = user::all();
        return response()->json($user);
    }

Now run get api in postman for fetching data

Show Function : For fetching particular record to database

public function show($id)
    {
        $user = user::findOrFail($id);
        return response()->json($user);
    }

Update Function: Create Put/Update API for edit/update records to database using usercontroller.

 app\Http\Controllers\UserController.php

public function update(Request $request, $id)
    {
        
        $user = User::find($id);
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = $request->password;
        $user->update();

        return response()->json($user);
    }

Destroy Function : Create Delete API for delete any records to database using usercontroller.

 app\Http\Controllers\UserController.php

public function destroy($id)
    {
        $user = User::findOrFail($id);
        $user->delete();
        return response()->json("Record Delete Successfully");
    }

Compete Controller Code:

<?php

namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = user::all();
        return response()->json($user);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:50',
            'email' => 'required',
            'password' => 'required'
          ]);
      
          $user = new user([
            'name' => $request->get('name'),
            'email' => $request->get('email'),
            'password' => $request->get('password'),
          ]);
      
          $user->save();
      
          return response()->json($user);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $user = user::findOrFail($id);
        return response()->json($user);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        
        $user = User::find($id);
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = $request->password;
        $user->update();

        return response()->json($user);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $user = User::findOrFail($id);
        $user->delete();
        return response()->json("Record Delete Successfully");
    }
}

2 thoughts on “Create Laravel CRUD REST API

  • Pingback: How to fetch data in Angular using API - BlogsHub

  • October 20, 2024 at 12:58 am
    Permalink

    excellent publish, very informative. I wonder why the opposite specialists of this sector do not notice this. You should continue your writing. I’m sure, you have a great readers’ base already!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *