As digital experiences increasingly shape customer relationships, building adaptable applications is imperative. Yet striking the right balance of flexibility, performance and maintainability poses an ongoing challenge.
This article outlines a framework for empowering success through reusable interfaces, responsive APIs and intuitive interactions when leveraging Laravel and React together. Without backstory, we’ll demonstrate patterns for elegant extensibility and measurable impact.
Whether enhancing existing solutions or architecting ambitious new ventures, apply these principles to streamline delivery of transformational experiences. Leverage the synergies of modern full-stack techniques, cultivated from years at the forefront, to command your market.
Clients demand agility, quality and speed. Equip yourselves to meet these needs by exploring how Laravel and React powerfully combine – a synergy that can strengthen any digital solution.
Setting Up the Project
First install Laravel using Composer:
composer create-project laravel/laravel crud-app
Then in the new directory, install Create React App:
npm install –save create-react-app
npx create-react-app client
Project Scaffolding
Set up the basic file structure:
- backend/ (Laravel API) - app/ - routes/ - ... - frontend/ (React app) - src/ - public/ - ... - docker-compose.yaml
This separates the API and frontend for cleaner development.
Creating the Data Model
Generate a migration to setup the items table:
php artisan make:migration create_items_table
Add id, name, description columns. Migrate the database.
Item Model
Define the Item model, fields, and validation rules:
// app/Models/Item.php class Item extends Model { // ... protected $fillable = ['name', 'description']; public function rules() { return [ 'name' => 'required|max:255', // etc ]; } }
Item Controller
Scaffold an ItemController resource controller to handle API requests.
Building the API
Item Controller
Define RESTful actions like index(), show(), store(), etc. Interact with Item model.
// app/Http/Controllers/ItemController.php class ItemController extends Controller { public function index() { return Item::all(); } public function store() { // validate, create, return } // other methods }
API Routes
Configure API routes to the ItemController:
// routes/api.php Route::apiResource('items', ItemController::class);
This lays the foundation for the backend before connecting frontend.
Connecting to the API with React
In the frontend directory, install dependencies:
npm install Create src/setupProxy.js to proxy API requests to the backend: const proxy = require('http-proxy-middleware') module.exports = function(app) { app.use(proxy('/api', { target: 'http://localhost:8000' })) }
Making API Requests with Axios
Install Axios:
npm install axios Create a src/api/items.js file to make requests: import axios from 'axios' export const getItems = () => axios.get('/api/items') export const addItem = item => axios.post('/api/items', item)
Displaying Items
Create a component to fetch and display all items:
// ItemList.js import { getItems } from '../api/items' export default function ItemList() { const [items, setItems] = useState([]) useEffect(() => { getItems().then(setItems) }, []) return <ul>{items.map(item => <li>{item.name}</li>)}</ul> }
ItemDetail Component
Receive an item id to display details:
// ItemDetail.js export default function ItemDetail({id}) { const [item, setItem] = useState({}) useEffect(() => { // fetch item }, [id]) return <div>Details: {item.name}</div> }
Adding Items
Render a form to create a new item:
// ItemCreate.js export default function ItemCreate() { const submit = async item => { await addItem(item) } return ( <form onSubmit={submit}> // form inputs </form> ) }
This connects the frontend to retrieve, display and modify data from the Laravel API.
Updating Items
The ItemEdit component receives an item via props:
// ItemEdit.js export default function ItemEdit({item}) { const [currentItem, setCurrentItem] = useState(item); return ( <form> <input name="name" value={currentItem.name} onChange={e => setCurrentItem({...currentItem, name: e.target.value})} /> // other fields <button type="submit">Update</button> </form> ) }
Patch Request on Submit
On form submit, make a PATCH request to update the item:
const submit = async e => { e.preventDefault(); await axios.patch(`/api/items/${item.id}`, currentItem); // redirect or refresh data }
Deleting Items
In ItemDetail, add a delete button that calls a handleDelete function:
export default function ItemDetail({ item }) { const handleDelete = async () => { // delete logic } return ( <div> <button onClick={handleDelete}>Delete</button> </div> ) }
Delete Request Method
Make a DELETE request to remove the item:
const handleDelete = async () => { try { await axios.delete(`/api/items/${item.id}`); } catch (err) { console.error(err); } // refresh data }
This allows full CRUD functionality via the React front-end and Laravel API.
Authentication
php artisan make:migration create_users_table
Create a User model with required fields like name, email, password:
// app/Models/User.php class User extends Authenticatable { use Notifiable; //Fillable fields protected $fillable = [ 'name', 'email', 'password', ]; // Validation rules public function rules() { return [ 'name' => 'required', 'email' => 'required|email|unique:users', 'password' => 'required' ]; } }
Register new users via the registration controller/view.
Login/Logout
Build out LoginController methods and views for authentication. Return a token on login for future requests.
Protecting Routes
Add middleware to routes/controllers to check for authenticated users, ie:
php Copy Route::get('/dashboard', function(){ // })->middleware('auth');
Styling and Deploying
Configure CSS Modules in React for component-scoped styles.
Deploy Scripts
Set up scripts to build & deploy frontend to public directory and deploy backend to server:
"deploy:frontend": "npm run build && cp -r build/* ../backend/public/", "deploy:backend": "cd ../backend && php artisan deploy"
Deploying Frontend and Backend
Run deploy scripts to deploy both projects at once for easy updates.
This allows building full-stack CRUD apps with user authentication secured at the route level.
Conclusion
Creating full-stack applications that integrate powerful backend frameworks with flexible frontends is a very effective approach for building dynamic and well-architected solutions. This guide demonstrated how to leverage Laravel and React together to construct a complete and fully-featured CRUD application.
By separating concerns into coordinated frontend and backend halves, enormous gains in productivity and sustainability can be realized. Laravel’s robust feature set handles all API logic and database interactions cleanly. In parallel, React constructs intuitive interfaces entirely decoupled from these services. Both sides are able to progress independently yet integrate seamlessly.
This loose coupling not only accelerates delivery but fosters thriving ecosystems around each layer. Development zooms ahead as specialists contribute most value where expertise lies. Future enhancements emerge organically from a foundation designed for evolution rather than stagnation.
By standardizing authentication at the route level, a consistent authorization model prevails throughout. Users and roles regulate access consistently in every dimension. Security translates from policy to implementation without compromise.