Hey friends, As we know Laravel is the best of one Framework of PHP. Laravel configured Vue, React and by using laravel we can setup dynamic and single page application. Here in this tutorials we are creating a CRUD application by using laravel + React. In this application, we will managing such of some features of React and Laravel.
Install Laravel by using below command.
composer create-project laravel/laravel laravel-react-crud
composer require laravel/ui
php artisan ui react
Create the User component inside the components folder like below path.
import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter as Routes, Route,Redirect, Switch } from "react-router-dom"; import HeaderNav from "./HeaderNav"; import CreateEmployee from "./Employee/CreateEmployee"; import ListEmployee from "./Employee/ListEmployee"; import NotFoundPage from "./NotFoundPage"; import axios from 'axios'; window.$axios = axios; function User() { return ( <> <Routes> <HeaderNav /> <Switch> <Route path="/" exact={true} component={ListEmployee} /> <Route path="/employee/create" component={CreateEmployee} /> <Route path="*" component={NotFoundPage} /> </Switch> </Routes> </> ); } export default User; // DOM element if (document.getElementById("app")) { ReactDOM.render(<User />, document.getElementById("app")); }
Change the app\Exceptions\Handler.php file, add render method below of the register methdod.
<?php public function render($request, Throwable $exception) { if ($this->isHttpException($exception)) { if ($exception->getStatusCode() == 404) { return response()->view('index'); } } return parent::render($request, $exception); }
index.blade.php file will be look like that.
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CRUD operation by using Laravel + React</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"> <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> </head> <body> <script> window.api_url = "{{ url('api/') }}"; </script> <!-- React root DOM --> <div id="app"></div> <!-- React JS --> <script src="{{ asset('js/app.js') }}" defer></script> </body> </html>
resources\js\components\Employee\CreateEmployee.js
import React, { useState, useEffect } from "react"; import ReactDOM from "react-dom"; import { useHistory } from "react-router-dom"; function CreateEmployee(props) { const history = useHistory(); const [employeeDetails, setEmployeeDetails] = useState({ first_name:'Jitu', last_name:'Webkul', email:'jitendrasahu17996@gmail.com', mobile:'8887603331', password:'123', accept_agreement:true, }); const [ msgResponse , setMsgResponse] = useState({ msgStatus:false, msg:'', msgClass:'', }); const handleChange = (e) =>{ let fieldName = e.target.name; let valueName = e.target.value; setEmployeeDetails({ ...employeeDetails, [fieldName]: valueName }); } const userSubmit = (e,props) => { e.preventDefault(); let createEmployeeUrl = `${window.api_url}/employee/create`; window.$axios.post(createEmployeeUrl , employeeDetails) .then( (res) => { if(res.data.status == 200){ var alertClass = 'alert alert-success'; }else if(res.data.status == 400){ var alertClass = 'alert alert-danger'; } setMsgResponse({ ...msgResponse, msgStatus:res.data.status , msg:res.data.msg, msgClass:alertClass}); }); } const showMsg = (props) =>{ if(msgResponse.msgStatus){ if(msgResponse.msgStatus == 200){ setTimeout(function(){ history.push('/'); } , 1000) } return ( <div className={msgResponse.msgClass} role="alert"> {msgResponse.msg} </div> ); } } return ( <> <div className="container mt-3 mb-3"> <div className="row"> <h2>Create Emplyees</h2> </div> {showMsg()} <form onSubmit={userSubmit}> <div className="row"> <div className="col-4"> <div className="form-group"> <label htmlFor="first_name">First Name</label> <input type="text" className="form-control" id="first_name" name="first_name" value={employeeDetails.first_name} onChange={handleChange} placeholder="First Name" /> </div> </div> <div className="col-4"> <div className="form-group"> <label htmlFor="last_name">Last Name</label> <input type="text" className="form-control" id="last_name" name="last_name" value={employeeDetails.last_name} onChange={handleChange} placeholder="Last Name" /> </div> </div> </div> <div className="row"> <div className="col-4"> <div className="form-group"> <label htmlFor="email">Email address</label> <input type="text" className="form-control" id="email" name="email" value={employeeDetails.email} onChange={handleChange} placeholder="Email" /> </div> </div> <div className="col-4"> <div className="form-group"> <label htmlFor="mobile">Mobile Number</label> <input type="text" className="form-control" id="mobile" name="mobile" value={employeeDetails.mobile} onChange={handleChange} placeholder="Mobile" /> </div> </div> </div> <div className="row"> <div className="col-8"> <div className="form-group"> <label htmlFor="password">Password</label> <input type="text" className="form-control" id="password" name="password" value={employeeDetails.password} onChange={handleChange} placeholder="Password" /> <small id="emailHelp" className="form-text text-muted">Create strong password.</small> </div> </div> </div> <div className="form-group form-check"> <input type="checkbox" checked={employeeDetails.accept_agreement} onChange={handleChange} className="form-check-input" id="exampleCheck1" /> <label className="form-check-label" htmlFor="exampleCheck1">Accept all Agreement</label> </div> <button type="submit" className="btn btn-primary mt-2">Submit</button> </form> </div> </> ); } export default CreateEmployee;
Install Laravel mix.
npm install
npm run dev
npm run watch
Check the webpack.mix.js file
const mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ mix.js('resources/js/app.js', 'public/js') .react() .sass('resources/sass/app.scss', 'public/css');
Now React has been successfull installed in laravel. Now run the below command to run the laravel react project
php artisan serve
Open the below command in browser
http://127.0.0.1:8000/
Download installed laravel React Setup from this github link.
https://github.com/jeetu-sah/laravel-react-crud