1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel8 ReactHooks & MySQL Create処理

Last updated at Posted at 2021-03-14

#やりたいこと
フロントはReactHooksを使用して、LaravelはバックエンドでAPIサーバー処理をおこなう。
サーバからデータの取得、サーバ上のデータの更新はaxiosを使用。
フォームからの入力をDBに保存するまで。

#完成図

e147bdcac8ccf1b01931c53e89227bdd.png

開発環境

  • Laravel 8.0
  • php 7.3
  • MySQL 8

###State

  • const [ name, setName ] = useState(null);

入力値name(名前)のState

  • const [ email, setEmail ] = useState(null);

入力値email(メールアドレス)のState

  • const [ city, setCity ] = useState(null);

入力値city(住所)のState

  • const [ address, setAddress ] = useState(null);

入力値address(市区町村)のState

  • const [ phone, setPhone ] = useState(null);

入力値phone(電話番号)のState

####入力フォーム
map処理はkeyを明示する必要があるので注意

keyの明示についてはVirtualDOMのdiffから実際のDOMに反映させるときに最小限の変更にするために使われる。

form

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 saveEmployee = async () => {

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

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

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

      <div className="row">
        <div className="col-md-6 mb-3">
          <label htmlFor="email">Email</label>
          <input type="email" className="form-control" placeholder="you@example.com"
            onChange={(event)=>setEmail(event.target.value)} />
        </div>
      </div>

      <div className="row">
        <div className="col-md-6 mb-3">
          <label htmlFor="phone">City </label>
          <select id="inputState" className="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 className="row">
        <div className="col-md-6 mb-3">
          <label htmlFor="address">Address</label>
          <input type="text" className="form-control" placeholder="1234 Main St"
            onChange={(event)=>setAddress(event.target.value)} />
        </div>
      </div>

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

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

export default Form;

saveEmployee押化後、axiosのemployee.saveが呼び出されてlocalhost:8000/api/employee/createにPOSTする。

axios通信

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

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
api.php

<?php

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

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

Route::post('/employee/create', 'App\Http\Controllers\API\EmployeeController@create');

Laravel側のControllerが呼び出され、実際に処理をするcreateアクションを呼び出します。

保存処理の最後にはresponseを返してあげる。今回は動作確認のため、失敗時にエラーメッセージのみを返しています。

コントローラー

EmployeeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employee;

class EmployeeController extends Controller
{
    public function index(){
        return view("employee");
      }

      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'];
  
          Employee::insert($insert);
  
          $response['message'] = "Save succesful";
          $response['succes'] = true;
  
        } catch (\Exception $e) {
          $response['message'] = $e->getMessage();
          $response['error'] = true;
        }
         
        return $response;
      }
}

createアクションはこのような流れで実装できます

指摘などがございましたらコメントで教えていただけると幸いです^_^

おわり

次はレコードをmapで繰り返し表示する方法など記事にしていこうと思います〜!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?