Home Laravel 9 Laravel 9 React Complete CRUD Application

Laravel 9 React Complete CRUD Application

20 min read
0
0
2,071

This tutorial will teach you how to make simple Crud Application using Laravel 9 with React Frontend application using Api access Crud application.

First Step What you have to do is you to divide the Front-End and Back-End.

Front-End – React JS

Back-End – Laravel

Create the folder myprojects. inside the folder frond end project you maintaing with the seperate folder.
backend project

Install Laravel 9

Create  a new Project type  the command on the command prompt  . I create the project name Office

type the command office-backend

composer create-project laravel/laravel office-backend

After Type the Command you have to wait till the project has been created. in this example i gave the project name as office-app. instead of that you have to give office-backend

after created the project you will get the success message i attached the screen shot below.

Second Step : You have to create the database so you have to go the mysql by typing the browser address bar http://localhost/phpmyadmin  then you will get the database dashboard after that you have to create the new database. I attached the screen shot image below.in this example i have create the database name is office.

after create the database.you have to open your project into Visual Studio Code Editor. after that you have to configure the database details into Laravel project .env file. i attach the database details below.

in this section DB-DATABASE  you have to give the name of the database which you have created.

After that run and check the application of the welcome screen of Laravel framework look like this.

Create Migration

Create the tables by typing this command

php artisan make:migration create_employees_table

After that inside  database folder create_employees_table.php  migrations  file has been created.  you can open the file.

Click and open the create_employees_table.php file. you can see by default look like this.

public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }

then you have to create the following fields.

$table->string(‘name’);

$table->string(‘address’);

$table->string(‘mobile’);

inside the function up() .function i shown in below clearly.

   public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('address');
            $table->string('mobile');
            $table->timestamps();
        });
    }

After that type the following command on the console.

php artisan migrate

the table has been created.you can check on the database.

Create Controller

Create the controller name which is EmployeeController

php artisan make:controller EmployeeController

after that open up the EmployeeController

EmployeeController

All view pages are manageable through the Controller. you have to add the Model namespace here

use App\Models\Employee  Data is coming from the database via the Model. Model is the part where communicate the with database to pass the data to the controller.

In the Employee Controller we have 4 different  functions(Index,Store,Update,destroy) shall able to perform  the Crud operations.

Lets Learn by On by One

index() Function : inside the index function we have written following codes.

$employees = Employee::all(); 
return response()->json($employees);

Employee::all(); in this code snippet describes get all the Employee details from Model Class which name is Employee and assign to $employees variable and pass as Json Format.

store() Function : public function store(Request $request) : in this code snippet describes when fill the form on the Front End(Vue JS) click Save button all the form data come and store variable $request.then set Form variable to database tables columns then assign to $employees variables.after that call $employees->save(); then record insert successfully get the response as json format.

public function store(Request $request)
    {
        $employees = new Employee([
            'name' => $request->input('name'),
            'address' => $request->input('address'),
            'mobile' => $request->input('mobile'),

        ]);
        $employees->save();
        return response()->json('Employee created!');
    }

Update() Function :  public function update(Request $request, $id) : in this code snippet describes when we make the changes of the  form on the Front End(Vue JS) click Save button all the form data come and store variable $request  along the $id variable. then set all the Form variable to database tables columns match with id find($id); variable.after that call $employees->update(); then record update successfully get the response as json format.

public function update(Request $request, $id)
    {
       $employees = Employee::find($id);
       $employees->update($request->all());
       return response()->json('Employee updated');
    }

destroy($id) Function  : public function destroy($id) in this code snippet describes when click the delete button on the table row of the Front End(Vue JS) application  get the id of row record and find($id); method to find the id. then delete the entire row records.

public function destroy($id)
    {
        $employees = Employee::find($id);
        $employees->delete();
        return response()->json(' deleted!');
    }

Full Code of the EmployeeController

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;

class EmployeeController extends Controller
{  
    public function index()
    {
        $employees = Employee::all();
        return response()->json($employees); 
    }   
    public function store(Request $request)
    {
        $employees = new Employee([
            'name' => $request->input('name'),
            'address' => $request->input('address'),
            'mobile' => $request->input('mobile'),
        ]);
        $employees->save();
        return response()->json('Employee created!');
    }
    public function show($id)
    {
        $contact = Employee::find($id);
        return response()->json($contact);
    }
    public function update(Request $request, $id)
    {
       $employees = Employee::find($id);
       $employees->update($request->all());
       return response()->json('Employee updated');
    }
    public function destroy($id)
    {
        $employees = Employee::find($id);
        $employees->delete();
        return response()->json(' deleted!');
    }
}

Create Model

Model is used to get the data from the database.

Create the Model name which is Employee

php artisan make:model Employee

After Model is Created the look like this. Code inside Model Class(app\Models)

Change it as like this

Add the namespace above

<?php

namespace App\Models;

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

class Employee extends Model
{
    protected $table = 'employees';
    protected $primaryKey = 'id';
    protected $fillable = ['name', 'address', 'mobile'];   

    use HasFactory;
}

After that set Routes

go to the folder Routes inside folder select Routes file as api.php 

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\EmployeeController;


Route::get('/employees',[App\Http\Controllers\EmployeeController::class, 'index']);

Route::post('/save',[App\Http\Controllers\EmployeeController::class, 'store']);

Route::put('/update/{id}',[App\Http\Controllers\EmployeeController::class, 'update']);

Route::delete('/delete/{id}',[App\Http\Controllers\EmployeeController::class, 'destroy']);


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

Now BackEnd Part is Done. let’s start the Frond-End Part

React

Installing React

npx create-react-app front-end

After complete the installation and run the project using following command.

npm start run

Now you see the React Welcome Page.

After that open the React project into VS code editor.

now you can see the following file structure

After that install the Bootstrap by typing the following command

npm i bootstrap

After that install the axios by typing the following command

npm i axios

Creating a new Component Employee.

import axios from 'axios';
import {useEffect, useState } from "react";

function Employee()
{
  const [id, setId] = useState('');
  const [name, setName] = useState("");
  const [address, setAddress] = useState("");
  const [mobile, setMobile] = useState("");
  const [employees, setUsers] = useState([]);

useEffect(() => {
  (async () => await Load())();
  }, []);

  async function  Load()
  {
     const result = await axios.get(
         "http://127.0.0.1:8000/api/employees");
         setUsers(result.data);
         console.log(result.data);
  }
 
    
     async function save(event)
    {
        event.preventDefault();
    try
        {
         await axios.post("http://127.0.0.1:8000/api/save",
        {
        
          name: name,
          address: address,
          mobile: mobile
        
        });
          alert("Employee Registation Successfully");
          setId("");
          setName("");
          setAddress("");
          setMobile("");
          Load();
        
        }
    catch(err)
        {
          alert("User Registation Failed");
        }
   }
   async function editEmployee(employees)
   {
    setName(employees.name);
    setAddress(employees.address);
    setMobile(employees.mobile); 
 
    setId(employees.id);
    
   }



   async function DeleteEmployee(id)
   {
       
        await axios.delete("http://127.0.0.1:8000/api/delete/" + id); 
        alert("Employee deleted Successfully");
        Load();
   
   }



   async function update(event)
   {
    event.preventDefault();

   try
       {
        
        await axios.put("http://127.0.0.1:8000/api/update/"+ employees.find(u => u.id === id).id || id,
       {
         id: id,
         name: name,
         address: address,
         mobile: mobile
       
       });
         alert("Registation Updateddddd");
         setId("");
         setName("");
         setAddress("");
         setMobile("");
         Load();
       
       }
   catch(err)
       {
         alert("User Registation Failed");
       }
  }

  return (
    <div>
       <h1>Employee Details</h1>
       <div class="container mt-4" >
          <form>
              <div class="form-group">
               <input  type="text" class="form-control" id="employee_id" hidden
               value={id}
               onChange={(event) =>
                {
                  setId(event.target.value);      
                }}
               
               />
                <label>Employee Name</label>
                <input  type="text" class="form-control" id="employeeName"
                value={name}
                onChange={(event) =>
                  {
                    setName(event.target.value);      
                  }}
                />
              </div>
              <div class="form-group">
                <label>Employee Address</label>
                <input  type="text" class="form-control" id="employeeAddress" 
                 value={address}
                  onChange={(event) =>
                    {
                      setAddress(event.target.value);      
                    }}
                />
              </div>

              <div class="form-group">
                <label>Mobile</label>
                <input type="text" class="form-control" id="employeeMobile" 
                  value={mobile}
                onChange={(event) =>
                  {
                    setMobile(event.target.value);      
                  }}
                />
              </div>

                 <div>
              <button   class="btn btn-primary mt-4"  onClick={save}>Register</button>
              <button   class="btn btn-warning mt-4"  onClick={update}>Update</button>
              </div>   
            </form>
          </div>

<table class="table table-dark" align="center">
  <thead>
    <tr>
      <th scope="col">Employee Id</th>
      <th scope="col">Employee Name</th>
      <th scope="col">Employee Address</th>
      <th scope="col">Employee Mobile</th>
      
      <th scope="col">Option</th>
    </tr>
  </thead>
       {employees.map(function fn(employee)
       {
            return(
            <tbody>
                <tr>
                <th scope="row">{employee.id} </th>
                <td>{employee.name}</td>
                <td>{employee.address}</td>
                <td>{employee.mobile}</td>        
                <td>
                    <button type="button" class="btn btn-warning"  onClick={() => editEmployee(employee)} >Edit</button>  
                    <button type="button" class="btn btn-danger" onClick={() => DeleteEmployee(employee.id)}>Delete</button>
                </td>
                </tr>
            </tbody>
            );
            })}
            </table>
       </div>
            );
        }
 
export default Employee;

Paste code inside the app.js

App.js

import Employee  from './components/Employee';
import 'bootstrap/dist/css/bootstrap.min.css';

function App() {
  return (
    <div className="App">
        <Employee />
    </div>
  );
}

export default App;

i have attached the video link below. which will do this tutorials step by step.

 

 

    Load More Related Articles
    Load More By admin
    Load More In Laravel 9

    Leave a Reply

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

    Check Also

    Build a Full-Stack Node.js MongoDB CRUD App with JWT Authentication

    In this tutorial, we will teach the process of building a full-stack application using Nod…