Implementasi ReactJS dengan Laravel
Dipostingan kali ini, saya akan melanjutkan materi CRUD Laravel yang diimplementasikan dengan ReactJS.
Sebelum itu, ada beberapa yang harus dipersiapkan, antara lain:
1. Komputer kalian sudah terinstal Node.js
2. Komputer kalian sudah terinstal composer
3. Terminal
3. Teks Editor (saya menggunakan Visual Studio Code)
4. Standby internet, karena nanti ada beberapa library yang kita instal mungkin membutuhkan koneksi internet.
5. Komputer kalian sudah terinstal Xampp
Langsung saja kita buat projeknya.
1. Install node.js, jika belum, silahkan download di link https://nodejs.org/en/
2. Buat projek laravel kalian sesuai dengan direktori yang kalian inginkan dengan mengetik diterminal
composer create-project --prefer-dist laravel/laravel crud-react
3. Jika sudah selesai, masuk ke direktori laravel yang kalian buat dan ketik
composer require laravel/ui --dev
4. Silahkan menunggu karena ini membutuhkan waktu yang agak sedikit lama.
5. Jika sudah selesai, ketik
php artisan ui react
Setelah sukses, ketik
npm install
6. Setelah selesai, ketik
npm install axios –save
7. Buka 2 terminal, karena 1 terminal untuk npm dan satu lagi untuk laravel. Karena Visual Studio Code sudah ada terminal, maka saya cukup buka 1 terminal command prompt.
8. Buka xampp-controlpanel yang sudah kalian install, lalu start Apache dan MySql nya.
9. Buka web browser kalian, masuk ke localhost/phpmyadmin, kemudian buat database kalian. (disini saya membuat database dengan nama hr yang sudah ada tabel tabel nya).
Disini saya hanya menggunakan tabel employees, departments, dan jobs saja yang sudah terisi data-datanya.
10. Kemudian buka project kalian dieditor, masuk ke di direktori resource/views, lalu buat folder baru dengan nama
layouts
11. Kemudian didalam folder layouts, buat file baru dengan nama
app.blade.php
12. Isikan script berikut ini
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<title>Laravel</title> | |
<link href="{{ asset('/css/app.css') }}" rel="stylesheet" type="text/css"> | |
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> | |
<!-- Fonts --> | |
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet"> | |
<!-- Styles --> | |
</head> | |
<body> | |
<div class="container"> | |
<nav class="navbar navbar-expand-lg navbar-light bg-light"> | |
<a class="navbar-brand" href="#">Navbar</a> | |
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> | |
<span class="navbar-toggler-icon"></span> | |
</button> | |
<div class="collapse navbar-collapse" id="navbarNavAltMarkup"> | |
<div class="navbar-nav"> | |
<a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a> | |
<a class="nav-item nav-link" href="/employees">Employees</a> | |
</div> | |
</div> | |
</nav> | |
</div> | |
@yield('content') | |
<script src="/js/app.js"></script> | |
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> | |
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> | |
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> | |
</body> | |
</html> |
13. Kemudian pada direktori resourse/views, ganti isi file welcome.blade.php menjadi seperti berikut ini.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@extends('layouts.app') | |
@section('content') | |
<div class="container mt-5"> | |
<div class="container-fluid justify-content-center"> | |
<div class="row"> | |
<div class="jumbotron"> | |
<h1 class="display-4">Hello, world!</h1> | |
<p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p> | |
<hr class="my-4"> | |
<p>It uses utility classes for typography and spacing to space content out within the larger container.</p> | |
<a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a> | |
</div> | |
</div> | |
</div> | |
</div> | |
@endsection |
14. Kemudian pada direktori resourse/views, buat 3 file, yaitu :
create.blade.php
edit.blade.php
employees.blade.php
15. Pada create.blade.php ketikan script berikut ini
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@extends('layouts.app') | |
@section('content') | |
<div class="container-fluid justify-content-center"> | |
<div class="row"> | |
<div id="create" class="col-lg-12 mt-5"></div> | |
</div> | |
</div> | |
@endsection |
16. Pada edit.blade.php ketikan script berikut ini
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@extends('layouts.app') | |
@section('content') | |
<div class="container-fluid justify-content-center"> | |
<div class="row"> | |
<div id="edit" class="col-lg-12 mt-5" data-id="{!! $id !!}"></div> | |
</div> | |
</div> | |
@endsection |
17. Pada employees.blade.php ketikan script berikut ini
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@extends('layouts.app') | |
@section('content') | |
<div class="container-fluid justify-content-center"> | |
<div class="row"> | |
<div id="app" class="col-lg-12 mt-5"></div> | |
</div> | |
</div> | |
@endsection |
19. Buka terminal untuk laravel (saya cukup buka di Visual Studio Code), ketik script berikut ini untuk membuat controller dan model nya.
20. Kita akan mengisi script untuk model, Employee terlebih dahulu. Masuk kedirektori app, buka Employee.php isikan script berikut
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Employee extends Model | |
{ | |
protected $primaryKey = 'employee_id'; | |
public $timestamps = false; | |
protected $fillable = ['employee_id', 'first_name', 'last_name', 'email', 'phone_number', 'hire_date', 'job_id', 'salary', 'commission_pct', 'manager_id', 'department_id']; | |
} |
21. Masuk kedirektori app, buka Department.php isikan script berikut
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Department extends Model | |
{ | |
protected $primaryKey = 'department_id'; | |
protected $fillable = ['department_id', 'department_name', 'manager_id', 'location_id']; | |
} |
22. Masuk kedirektori app, buka Job.php isikan script berikut
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Job extends Model | |
{ | |
// protected $primaryKey = 'job_id'; | |
protected $fillable = ['job_id', 'job_title', 'min_salary', 'max_salary']; | |
} |
23. Maaf saya ada yg lupa, kita koneksikan dulu projek Laravel kita ke Database dengan menyeting file .env nya.
24. Yang saya kotakin dan garis bawahi, sesuaikan dengan set Database kalian.
25. Okey lanjut lagi
26. Buka terminal kalian, kita akan membuat controller yg mengontrol view nya saja. Ketik script berikut ini
27. Masuk ke direktori app/Http/Controllers, pada EmployeesController.php isikan script berikut ini
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use Illuminate\Http\Request; | |
use App\Employee; | |
use App\Job; | |
use App\Department; | |
class EmployeesController extends Controller | |
{ | |
/** | |
* Display a listing of the resource. | |
* | |
* @return \Illuminate\Http\Response | |
*/ | |
public function index() | |
{ | |
return view('employees'); | |
} | |
/** | |
* Show the form for creating a new resource. | |
* | |
* @return \Illuminate\Http\Response | |
*/ | |
public function create() | |
{ | |
return view('create'); | |
} | |
/** | |
* Store a newly created resource in storage. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @return \Illuminate\Http\Response | |
*/ | |
public function store(Request $request) | |
{ | |
// | |
} | |
/** | |
* Display the specified resource. | |
* | |
* @param int $id | |
* @return \Illuminate\Http\Response | |
*/ | |
public function show($id) | |
{ | |
// | |
} | |
/** | |
* Show the form for editing the specified resource. | |
* | |
* @param int $id | |
* @return \Illuminate\Http\Response | |
*/ | |
public function edit($id) | |
{ | |
return view ('edit', compact('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) | |
{ | |
// | |
} | |
/** | |
* Remove the specified resource from storage. | |
* | |
* @param int $id | |
* @return \Illuminate\Http\Response | |
*/ | |
public function destroy($id) | |
{ | |
// | |
} | |
} |
28. Masuk ke direktori app/Http/Controllers/Api, pada EmployeesController.php isikan script berikut ini
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers\Api; | |
use App\Employee; | |
use App\Job; | |
use App\Department; | |
use App\Http\Controllers\Controller; | |
use Illuminate\Http\Request; | |
class EmployeesController extends Controller | |
{ | |
/** | |
* Display a listing of the resource. | |
* | |
* @return \Illuminate\Http\Response | |
*/ | |
public function index() | |
{ | |
$employees = Employee::all(); | |
return response()->json($employees); | |
} | |
/** | |
* Show the form for creating a new resource. | |
* | |
* @return \Illuminate\Http\Response | |
*/ | |
public function create() | |
{ | |
$employees = Employee::all(); | |
$jobs = Job::all(); | |
$departments = Department::all(); | |
return response()->json( | |
array( | |
'employees' => $employees, | |
'jobs' => $jobs, | |
'departments' => $departments, | |
) | |
); | |
} | |
/** | |
* Store a newly created resource in storage. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @return \Illuminate\Http\Response | |
*/ | |
public function store(Request $request) | |
{ | |
$employees = Employee::orderBy('employee_id', 'DESC')->first(); | |
$employee_id = $employees->employee_id + 1; | |
Employee::create([ | |
'employee_id' => $employee_id, | |
'first_name' => $request->first_name, | |
'last_name' => $request->last_name, | |
'email' => $request->email, | |
'phone_number' => $request->phone_number, | |
'hire_date' => $request->hire_date, | |
'job_id' => $request->job_id, | |
'salary' => $request->salary, | |
'commission_pct' => $request->commission_pct, | |
'manager_id' => $request->manager_id, | |
'department_id' => $request->department_id | |
]); | |
} | |
/** | |
* Display the specified resource. | |
* | |
* @param \App\Employee $employee | |
* @return \Illuminate\Http\Response | |
*/ | |
public function show(Employee $employee) | |
{ | |
return response()->json($employee); | |
} | |
/** | |
* Show the form for editing the specified resource. | |
* | |
* @param \App\Employee $employee | |
* @return \Illuminate\Http\Response | |
*/ | |
public function edit(Employee $employee) | |
{ | |
$employees = Employee::all(); | |
$jobs = Job::all(); | |
$departments = Department::all(); | |
return response()->json( | |
array( | |
'employees' => $employees, | |
'jobs' => $jobs, | |
'departments' => $departments, | |
) | |
); | |
} | |
/** | |
* Update the specified resource in storage. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \App\Employee $employee | |
* @return \Illuminate\Http\Response | |
*/ | |
public function update(Request $request, Employee $employee) | |
{ | |
// return $request; | |
Employee::where('employee_id', $employee->employee_id) | |
->update([ | |
'first_name' => $request->first_name, | |
'last_name' => $request->last_name, | |
'email' => $request->email, | |
'phone_number' => $request->phone_number, | |
'hire_date' => $request->hire_date, | |
'job_id' => $request->job_id, | |
'salary' => $request->salary, | |
'commission_pct' => $request->commission_pct, | |
'manager_id' => $request->manager_id, | |
'department_id' => $request->department_id | |
]); | |
return response()->json($request); | |
} | |
/** | |
* Remove the specified resource from storage. | |
* | |
* @param \App\Employee $employee | |
* @return \Illuminate\Http\Response | |
*/ | |
public function destroy(Employee $employee) | |
{ | |
// return response()->json($employee); | |
Employee::destroy($employee->employee_id); | |
// // return $employee; | |
return response()->json('Employee Deleted Successfully!'); | |
} | |
} |
29. Masuk ke direktori routes, pada api.php isikan script berikut ini
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Http\Request; | |
/* | |
|-------------------------------------------------------------------------- | |
| 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:api')->get('/user', function (Request $request) { | |
return $request->user(); | |
}); | |
Route::resource('employees', 'Api\EmployeesController'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
|-------------------------------------------------------------------------- | |
| Web Routes | |
|-------------------------------------------------------------------------- | |
| | |
| Here is where you can register web routes for your application. These | |
| routes are loaded by the RouteServiceProvider within a group which | |
| contains the "web" middleware group. Now create something great! | |
| | |
*/ | |
Route::get('/', function () { | |
return view('welcome'); | |
}); | |
Route::resource('employees', 'EmployeesController'); |
32. Buka file Create.js yang sudah dibuat, lalu isikan script berikut ini
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
export default class Create extends React.Component{ | |
constructor(){ | |
super(); | |
this.state = { | |
first_name : '', | |
last_name : '', | |
email : '', | |
phone_number : '', | |
hire_date : '', | |
job_id : '', | |
salary : '', | |
commission_pct : '', | |
manager_id : '', | |
department_id : '' | |
} | |
} | |
componentDidMount() { | |
let $this = this; | |
axios.get('/api/employees/create').then(response => { | |
$this.setState({ | |
jobs: response.data.jobs, | |
employees: response.data.employees, | |
departments: response.data.departments | |
}) | |
}).catch(error => { | |
console.log(error) | |
}) | |
} | |
handleFirstNameChange(e){ | |
this.setState({ | |
first_name: e.target.value | |
}) | |
} | |
handleLastNameChange(e){ | |
this.setState({ | |
last_name: e.target.value | |
}) | |
} | |
handleEmailChange(e){ | |
this.setState({ | |
email: e.target.value | |
}) | |
} | |
handlePhoneNumberChange(e){ | |
this.setState({ | |
phone_number: e.target.value | |
}) | |
} | |
handleHireDateChange(e){ | |
this.setState({ | |
hire_date: e.target.value | |
}) | |
} | |
handleJobIdChange(e){ | |
this.setState({ | |
job_id: e.target.value | |
}) | |
} | |
handleSalaryChange(e){ | |
this.setState({ | |
salary: e.target.value | |
}) | |
} | |
handleCommissionChange(e){ | |
this.setState({ | |
commission_pct: e.target.value | |
}) | |
} | |
handleManagerIdChange(e){ | |
this.setState({ | |
manager_id: e.target.value | |
}) | |
} | |
handleDepartmentIdChange(e){ | |
this.setState({ | |
department_id: e.target.value | |
}) | |
} | |
handleSubmit(e){ | |
e.preventDefault(); | |
console.log(this.state) | |
axios.post('/api/employees', this.state).then(response => { | |
window.location = "/employees" | |
}).then(error => { | |
console.log(error) | |
}) | |
} | |
render(){ | |
return( | |
<div className="container col-5"> | |
<h2 className="mb-3">Add New Employee</h2> | |
<form className="mb-5" onSubmit={this.handleSubmit.bind(this)}> | |
<div className="form-group"> | |
<label htmlFor="first_name">First Name</label> | |
<input type="text" className="form-control" id="first_name" name="first_name" value={this.state.first_name} onChange={this.handleFirstNameChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="last_name">Last Name</label> | |
<input type="text" className="form-control" id="last_name" name="last_name" value={this.state.last_name} onChange={this.handleLastNameChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="email">Email</label> | |
<input type="email" className="form-control" id="email" name="email" value={this.state.email} onChange={this.handleEmailChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="phone_number">Phone Number</label> | |
<input type="number" className="form-control" id="phone_number" name="phone_number" value={this.state.phone_number} onChange={this.handlePhoneNumberChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="hire_date">Hire Date</label> | |
<input type="date" className="form-control" id="hire_date" name="hire_date" value={this.state.hire_date} onChange={this.handleHireDateChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="job_id">Job Name</label> | |
<select className="custom-select" defaultValue={'DEFAULT'} name="job_id" onChange={this.handleJobIdChange.bind(this)}> | |
<option value="DEFAULT">Open this select menu</option> | |
{this.state.jobs && this.state.jobs.map(jobs => | |
<option value={jobs.job_id}>{jobs.job_id}</option> | |
)} | |
</select> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="salary">Salary</label> | |
<input type="number" className="form-control" id="salary" name="salary" value={this.state.salary} onChange={this.handleSalaryChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="commission_pct">Commision Pct</label> | |
<input type="number" className="form-control" id="commission_pct" name="commission_pct" step="any" min="0" max="100" value={this.state.commission_pct} onChange={this.handleCommissionChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="manager_id">Manager Name</label> | |
<select className="custom-select" defaultValue={'DEFAULT'} name="manager_id" onChange={this.handleManagerIdChange.bind(this)}> | |
<option value="DEFAULT">Open this select menu</option> | |
{this.state.employees && this.state.employees.map(employees => | |
<option value={employees.employee_id}>{employees.first_name} {employees.last_name}</option> | |
)} | |
</select> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="department_id">Department Name</label> | |
<select className="custom-select" defaultValue={'DEFAULT'} name="department_id" onChange={this.handleDepartmentIdChange.bind(this)}> | |
<option value="DEFAULT">Open this select menu</option> | |
{this.state.departments && this.state.departments.map(departments => | |
<option value={departments.department_id}>{departments.department_name}</option> | |
)} | |
</select> | |
</div> | |
<button type="submit" className="btn btn-primary float-right mb-5">Submit</button> | |
</form> | |
</div> | |
) | |
} | |
} | |
if(document.getElementById('create')){ | |
ReactDOM.render(<Create/>, document.getElementById('create')) | |
} |
33. Buka file Edit.js yang sudah dibuat, lalu isikan script berikut ini
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
export default class Edit extends React.Component{ | |
constructor(){ | |
super(); | |
this.state = { | |
first_name : '', | |
last_name : '', | |
email : '', | |
phone_number : '', | |
hire_date : '', | |
job_id : '', | |
salary : '', | |
commission_pct : '', | |
manager_id : '', | |
department_id : '' | |
} | |
} | |
componentWillMount(){ | |
// let $this = this; | |
let id = this.props.id | |
axios.get("/api/employees/"+id).then(response => { | |
console.log(response.data) | |
var employee = response.data; | |
this.setState({ | |
first_name : employee.first_name, | |
last_name : employee.last_name, | |
email : employee.email, | |
phone_number : employee.phone_number, | |
hire_date : employee.hire_date, | |
job_id : employee.job_id, | |
salary : employee.salary, | |
commission_pct : employee.commission_pct, | |
manager_id : employee.manager_id, | |
department_id : employee.department_id | |
}) | |
}).catch(error => { | |
console.log(error) | |
}) | |
} | |
componentDidMount() { | |
// let $this = this | |
let id = this.props.id | |
axios.get("/api/employees/"+id+"/edit").then(response => { | |
this.setState({ | |
jobs: response.data.jobs, | |
employees: response.data.employees, | |
departments: response.data.departments | |
}) | |
}).catch(error => { | |
console.log(error) | |
}) | |
} | |
handleFirstNameChange(e){ | |
this.setState({ | |
first_name: e.target.value | |
}) | |
} | |
handleLastNameChange(e){ | |
this.setState({ | |
last_name: e.target.value | |
}) | |
} | |
handleEmailChange(e){ | |
this.setState({ | |
email: e.target.value | |
}) | |
} | |
handlePhoneNumberChange(e){ | |
this.setState({ | |
phone_number: e.target.value | |
}) | |
} | |
handleHireDateChange(e){ | |
this.setState({ | |
hire_date: e.target.value | |
}) | |
} | |
handleJobIdChange(e){ | |
this.setState({ | |
job_id: e.target.value | |
}) | |
} | |
handleSalaryChange(e){ | |
this.setState({ | |
salary: e.target.value | |
}) | |
} | |
handleCommissionChange(e){ | |
this.setState({ | |
commission_pct: e.target.value | |
}) | |
} | |
handleManagerIdChange(e){ | |
this.setState({ | |
manager_id: e.target.value | |
}) | |
} | |
handleDepartmentIdChange(e){ | |
this.setState({ | |
department_id: e.target.value | |
}) | |
} | |
handleSubmit(e){ | |
e.preventDefault(); | |
console.log(this.state) | |
let id = this.props.id | |
// console.log(id) | |
axios.patch('/api/employees/'+id, this.state).then(response => { | |
window.location = "/employees" | |
console.log(response.request) | |
}).then(error => { | |
console.log(error) | |
}) | |
} | |
render(){ | |
return( | |
<div className="container col-5"> | |
<h2 className="mb-3">Add New Employee</h2> | |
<form className="mb-5" onSubmit={this.handleSubmit.bind(this)}> | |
<div className="form-group"> | |
<label htmlFor="first_name">First Name</label> | |
<input type="text" className="form-control" id="first_name" name="first_name" value={this.state.first_name || ''} onChange={this.handleFirstNameChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="last_name">Last Name</label> | |
<input type="text" className="form-control" id="last_name" name="last_name" value={this.state.last_name || ''} onChange={this.handleLastNameChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="email">Email</label> | |
<input type="email" className="form-control" id="email" name="email" value={this.state.email || ''} onChange={this.handleEmailChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="phone_number">Phone Number</label> | |
<input type="number" className="form-control" id="phone_number" name="phone_number" value={this.state.phone_number || ''} onChange={this.handlePhoneNumberChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="hire_date">Hire Date</label> | |
<input type="date" className="form-control" id="hire_date" name="hire_date" value={this.state.hire_date || ''} onChange={this.handleHireDateChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="job_id">Job Name</label> | |
<select className="custom-select" value={this.state.job_id || ''} name="job_id" onChange={this.handleJobIdChange.bind(this)}> | |
<option value="DEFAULT">Open this select menu</option> | |
{this.state.jobs && this.state.jobs.map(jobs => | |
<option value={jobs.job_id}>{jobs.job_id}</option> | |
)} | |
</select> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="salary">Salary</label> | |
<input type="number" className="form-control" id="salary" name="salary" value={this.state.salary || ''} onChange={this.handleSalaryChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="commission_pct">Commision Pct</label> | |
<input type="number" className="form-control" id="commission_pct" name="commission_pct" step="any" min="0" max="100" value={this.state.commission_pct || ''} onChange={this.handleCommissionChange.bind(this)}/> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="manager_id">Manager Name</label> | |
<select className="custom-select" value={this.state.manager_id || ''} name="manager_id" onChange={this.handleManagerIdChange.bind(this)}> | |
<option value="DEFAULT">Open this select menu</option> | |
{this.state.employees && this.state.employees.map(employees => | |
<option value={employees.employee_id}>{employees.first_name} {employees.last_name}</option> | |
)} | |
</select> | |
</div> | |
<div className="form-group"> | |
<label htmlFor="department_id">Department Name</label> | |
<select className="custom-select" value={this.state.department_id || ''} name="department_id" onChange={this.handleDepartmentIdChange.bind(this)}> | |
<option value="DEFAULT">Open this select menu</option> | |
{this.state.departments && this.state.departments.map(departments => | |
<option value={departments.department_id}>{departments.department_name}</option> | |
)} | |
</select> | |
</div> | |
<button type="submit" className="btn btn-primary float-right mb-5">Update</button> | |
</form> | |
</div> | |
) | |
} | |
} | |
if(document.getElementById('edit')){ | |
var id = $("#edit").data("id"); | |
ReactDOM.render(<Edit id={id}/>, document.getElementById('edit')) | |
} |
34. Buka file Employee.js yang sudah dibuat, lalu isikan script berikut ini
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
export default class Employee extends React.Component{ | |
constructor(){ | |
super(); | |
this.state = { | |
data: [] | |
} | |
} | |
componentDidMount(){ | |
let $this = this; | |
axios.get('/api/employees').then(response => { | |
$this.setState({ | |
data: response.data | |
}) | |
}).catch(error => { | |
console.log(error) | |
}) | |
} | |
render(){ | |
return( | |
<div> | |
<h2>List Employee</h2> | |
<a href="/employees/create" className="btn btn-primary mt-3 mb-3">Add Employee</a> | |
<table className="table table-bordered"> | |
<thead> | |
<tr> | |
<th scope="col">#</th> | |
<th scope="col">Name</th> | |
<th scope="col">Email</th> | |
<th scope="col">Phone Number</th> | |
<th scope="col">Hire Date</th> | |
<th scope="col">Job Id</th> | |
<th scope="col">Salary</th> | |
<th scope="col">Commission Pct</th> | |
<th scope="col">Manager Id</th> | |
<th scope="col">Department Id</th> | |
<th scope="col">Action</th> | |
</tr> | |
</thead> | |
<tbody> | |
{this.state.data.map((employee, i) => ( | |
<EmployeeRow key={i} i={i} employee={employee} object={this}/> | |
))} | |
</tbody> | |
</table> | |
</div> | |
) | |
} | |
} | |
class EmployeeRow extends React.Component{ | |
deleteEmployee(employee, object){ | |
console.log(employee) | |
var $this = object | |
axios.delete('/api/employees/'+employee.employee_id).then(response => { | |
const newState = $this.state.data.slice(); | |
newState.splice(newState.indexOf(employee), 1) | |
$this.setState({ | |
data: newState | |
}) | |
// console.log(response) | |
}).catch(error =>{ | |
console.log(error) | |
}) | |
} | |
render(){ | |
return( | |
<tr key={this.props.i}> | |
<th scope="row">{this.props.i+1}</th> | |
<td>{this.props.employee.first_name} {this.props.employee.last_name}</td> | |
<td>{this.props.employee.email}</td> | |
<td>{this.props.employee.phone_number}</td> | |
<td>{this.props.employee.hire_date}</td> | |
<td>{this.props.employee.job_id}</td> | |
<td>{this.props.employee.salary}</td> | |
<td>{this.props.employee.commission_pct}</td> | |
<td>{this.props.employee.manager_id}</td> | |
<td>{this.props.employee.department_id}</td> | |
<td> | |
<a href={"/employees/"+this.props.employee.employee_id+"/edit"} className="btn btn-primary">Edit</a> || <a href="javascript:;" className="btn btn-danger" onClick={this.deleteEmployee.bind(this, this.props.employee, this.props.object)}>Delete</a> | |
</td> | |
</tr> | |
) | |
} | |
} | |
if(document.getElementById('app')){ | |
ReactDOM.render(<Employee/>, document.getElementById('app')) | |
} |
35. Buka direktori resource/js, buka file app.js lalu isikan script berikut ini
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* First we will load all of this project's JavaScript dependencies which | |
* includes React and other helpers. It's a great starting point while | |
* building robust, powerful web applications using React + Laravel. | |
*/ | |
require('./bootstrap'); | |
window.axios = require('axios'); | |
/** | |
* Next, we will create a fresh React component instance and attach it to | |
* the page. Then, you may begin adding components to this application | |
* or customize the JavaScript scaffolding to fit your unique needs. | |
*/ | |
require('./components/Employee'); | |
require('./components/Create'); | |
require('./components/Edit'); |
npm run watch
37. Buka terminal untuk laravel, jalankan perintah
php artisan serve
kemudian copy alamat nya kebrowser
38. Selesai.
Cukup sekian di postingan kali ini, jika ada error, silahkan tulis dikolom komentar.
Oh iya, ini hanya program sederhana, mungkin kalian bisa mengembangkannya kembali :D
Selamat mencobaaa...
Sayonaraaaa ^_^