ReactJS Hooks + Laravel 8 + MySQL + API REST CRUD #3 Create

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 create(Request $request){

      try {

        $insert['name_lastname'] = $request['name'];
        $insert['email'] = $request['email'];
        $insert['city'] = $request['city'];
        $insert['direction'] = $request['address'];
        $insert['phone'] = $request['phone'];
        $insert['rol'] = $request['rol'];

        Employee::insert($insert);

        $response['message'] = "Save succesful";
        $response['succes'] = true;

      } catch (\Exception $e) {
        $response['message'] = $e->getMessage();
        $response['succes'] = true;
      }
       
      return $response;
    }
}

Route
routes/api.php
Route::post('/employee/create', 'App\Http\Controllers\API\[email protected]');

React – Frontend

Component

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

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

function Form(){

  const [ name, setName ] = useState(null);
  const [ email, setEmail ] = useState(null);
  const [ city, setCity ] = useState(null);
  const [ address, setAddress ] = useState(null);
  const [ phone, setPhone ] = useState(null);
  const [ rol, setRol ] = useState(null);
  const [ listRol, setListRol ] = useState([]);

  useEffect(() => {
    async function fetchDataRol() {
      // load data from API
      const res = await employeeServices.list();
      setListRol(res.data)
    }
    fetchDataRol();
  },[]);

  const saveEmployee = async () => {

    const data = {
      name, email, city, address, phone, rol
    }
    const res = await employeeServices.save(data);

    if (res.success) {
      alert(res.message)
    }
    else {
      alert(res.message)
    }
  }

  return(
    <div>
      <div class="row">
        <div class="col-md-6 mb-3">
          <label for="firstName">Name employee </label>
          <input type="text" class="form-control" placeholder="Name"
            onChange={(event)=>setName(event.target.value)} />
        </div>
      </div>

      <div class="row">
        <div class="col-md-6 mb-3">
          <label for="email">Email</label>
          <input type="email" class="form-control" placeholder="[email protected]"
            onChange={(event)=>setEmail(event.target.value)} />
        </div>
      </div>

      <div class="row">
        <div class="col-md-6 mb-3">
          <label for="phone">City </label>
          <select id="inputState" class="form-control" onChange={(event)=> setCity(event.target.value)}>
             <option selected>Choose...</option>
             <option value="London">London</option>
             <option value="Madrid">Madrid</option>
             <option value="New York">New York</option>
          </select>
        </div>
      </div>

      <div class="row">
        <div class="col-md-6 mb-3">
          <label for="address">Address</label>
          <input type="text" class="form-control" placeholder="1234 Main St"
            onChange={(event)=>setAddress(event.target.value)} />
        </div>
      </div>

      <div class="row">
        <div class="col-md-6 mb-3">
          <label for="phone">Phone </label>
          <input type="text" class="form-control" placeholder="123467890"
              onChange={(event)=>setPhone(event.target.value)}  />
        </div>
      </div>

      <div class="row">
        <div class="col-md-6 mb-3">
					<label for="phone">Rol </label>
					<select id="inputState" class="form-control" onChange={(event)=> setRol(event.target.value)}>
             <option selected>Choose...</option>
             {
               listRol.map((item)=>{
                 return(
                   <option value={item.rol_id}>{item.rol_name}</option>
                 )
               })
             }
          </select>
        </div>
      </div>

      <div class="row">
        <div class="col-md-6 mb-3">
          <button class="btn btn-primary btn-block" type="submit"
          onClick={()=>saveEmployee()}>Save 2</button>
        </div>
      </div>
    </div>
  )
}

export default Form;

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.list = async () => {
  const urlList = baseUrl+"/role"
  const res = await axios.get(urlList)
  .then(response=> {return response.data })
  .catch(error=>{ return error; })
  return res;
}

employee.save = async (data) => {
  const urlSave= baseUrl+"/create"
  const res = await axios.post(urlSave,data)
  .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 *