ReactJS Hooks + Laravel 8 + MySQL + API REST CRUD #7 Delete

Laravel – Backend

Controller
app/Http/Controllers/EmployeeController.php
<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Role;
use App\Models\Employee; 

class EmployeeController extends Controller
{
    // ... ///

    public function delete($id){

      try {
        $res = Employee::where("id",$id)->delete();
        $response['res'] = $res;
        $response['message'] = "Deleted successful";
        $response['success'] = true; 
      } catch (\Exception $e) {
        $response['message'] = $e->getMessage();
        $response['success'] = false;
      }

      return $response;
    }
  
  
}

Route
routes/api.php
Route::delete('/employee/delete/{id}', 'App\Http\Controllers\API\EmployeeController@delete');

React – Frontend

Component

List.js
resources/js/components/employee/List.js
import React, { useEffect, useState } from 'react';

import employeeServices from "../../services/Employee"

import { Link } from "react-router-dom";

function List(){

  const [ listEmployee, setListEmployee ] = useState([]);

  useEffect(()=>{

    async function fetchDataEmployee(){
      const res = await employeeServices.listEmployee();
      setListEmployee(res.data);
    }

    fetchDataEmployee();
  },[]);

  const onClickDelete = async (i,id) => {

    var yes = confirm("are you sure to delete this item?");
    if (yes === true){

      const res = await employeeServices.delete(id)

      if (res.success) {
        alert(res.message) 
        const newList = listEmployee
        newList.splice(i,1)
        setListEmployee(newList);
      }
      else{
        alert(res.message);
      }
    }

  }

  return (
    <section>

      <table class="table">
        <thead class="thead-dark">
          <tr>
            <th scope="col">#</th>
            <th scope="col">Name</th>
            <th scope="col">Email</th>
            <th scope="col">City</th>
            <th scope="col">Address</th>
            <th scope="col">Phone</th>
            <th scope="col">Rol</th>
            <th scope="col">Action</th>
          </tr>
        </thead>
        <tbody>

        {
          listEmployee.map((item,i)=>{
            return(
              <tr>
                <th scope="row">{item.id}</th>
                <td>{item.name_lastname}</td>
                <td>{item.email}</td>
                <td>{item.city}</td>
                <td>{item.direction}</td>
                <td>{item.phone}</td>
                <td>{item.role.rol_name}</td>
                <td>
                  <Link to={"/employee/edit/"+item.id} class="btn btn-light"> Edit </Link>
                  <a href="#" class="btn btn-danger" onClick={()=>onClickDelete(i,item.id)}> Delete </a>
                </td>
              </tr>
            )
          })
        }


        </tbody>
      </table>
    </section>
  )
}

export default List;

Services

Employee.js
resources/js/components/Mainresources/js/services/Employee.js
const baseUrl = "http://localhost:8000/api/employee"
import axios from "axios";
const employee = {};

//...//

employee.delete = async (id) => {
  const urlDelete = baseUrl+"/delete/"+id
  const res = await axios.delete(urlDelete)
  .then(response=> { return response.data })
  .catch(error =>{ return error })
  return res;
}


export default employee

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *