Laravel v5.8 + ReactJS – Installation
Here is a real simple guide to creating a Laravel/React app, and getting the page loaded in no time.
This is part of a series of stories I am writing, which will set the basis for a simple CRUD app.
Assumptions: You need to have a few things already installed..
composer, nodejs, npm, mysql/php (can be installed using brew, and this guide), laravel just to start…
Create a new Laravel App
$ laravel new AppName
$ cd AppName
Setup Laravel for React
In the Laravel docs, we have the capability to switch out the default Vue scaffolding and replace it with what we need to use React, so lets do that now.
$ php artisan preset react# Now initialise our setup
$ npm install
$ npm run dev
Homepage
We need to trim the default bloat out and replace it with a simple setup to get our React app working. It is important that we add the CSRF token into our head, so our requests can be validated later on.
Our main page should look something like this
views/welcome.blade.php
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1"> <title>Example Site</title> <link rel="stylesheet" type="text/css" href="css/app.css"> <meta name="csrf-token" content="{{ csrf_token() }}"> </head>
<body>
<div id="example"></div> <script type="text/javascript" src="js/app.js"></script>
</body>
</html>
Example.js
Lets remove the default bloat, and add a classic Hello (React) World!
After this, we will need to run the npm run dev command to recompile our assets.
$ npm run dev
Create the new database
Since I am using MySQL, the commands go something like
$ mysql -uroot -p1234mysql > create database AppName;
# Query OK, 1 row affected (0.00 sec)mysql > exit;
.env
Update the .env to use the correct details for the database config. At minimum..
DB_DATABASE=AppName
DB_USERNAME=root
DB_PASSWORD=1234
Laravel Authentication
Laravel makes it super easier to get our user authentication and related pages setup, lets use artisan to get this done
$ php artisan make:auth
Before migrating
As I am running MySQL 5.6, I needed to update my AppServiceProvider.php to include the Schema::defaultStringLength(191); and namespace.
If you are running MySQL5.7 (or another database), you can skip this step
Migrating
$ php artisan migrate
Lets check out our site
$ php artisan serve
# Laravel development server started: <http://127.0.0.1:8001>
For continued compiling of our assets, use this command in another terminal (leave the one with artisan serve open too, otherwise requests got nowhere to go) 😅
$ npm run watch
And there we have it!
In less time than it takes to make a coffee, we have a database-connected Laravel/React app booted up and ready to Build something amazing (line taken from Laravel initiation sequence) 😬