Saturday, March 9, 2019

ReactJS > Load Different Component Based on Different Conditions

I want to load different component based on URL or as I think, any different condition. So if URL is myreact.com/user/1000 it should load AdminUserComponent and if URL is myreact.com/user/5000 it should load StaffUserComponent. Its just an example, we can handle any type of conditions based on situation.
So our Route would be like

<Route path="/user/:user_param" component={UserDecideWrapper} />
And the UserDecideWrapper is nothing but a if else condition block to decide which component will load or not.

class ComponentDecide extends MainActivity {
    render() {
        let id = parseFloat(this.props.match.params.id);
        if (isNaN(id)) {
            return <Home {...this.props}/>
        }
        if (id === 1000) {
            return <AdminUserComponent {...this.props}/>
        }
        return <StaffUserComponent {...this.props}/>
    }
}
{...this.props} indicated that props will be passed as constructor.

Install ReactJS along with Laravel 5.X along with higher version such 6.X

We need npm command, so for this we need to install NodeJS first, this will create NPM along with this, for windows users, go to https://nodejs.org/en/ and download your suitable installer and install if not alredy installed..
Now we will create an Laravel project first using following command (this will take some time):
composer create-project --prefer-dist laravel/laravel ReactJSLaravelTutorial


Laravel installed:

Now we need to initiate scaffolding with React. Luckily for us, there is a preset Artisan command we can use for that. The preset command was added in Laravel 5.5, which allows us to specify our JavaScript framework of choice.

php artisan preset react

After that, we need to install the JavaScript dependencies of our project. By default, package.json file is there, so we just need to type the following command to get the NPM dependencies.

Please run npm install && npm run dev to compile your fresh scaffolding.
We should now have an Example.js file inside resources/assets/js/components, which is a basic React component. Also, resources/assets/js/app.js has been updated to make use of the Example component.

Now go to your database manager, for example, phpMyAdmin or MySQL work bench and create one database.
Go to .env file and enter your database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db-laravel1
DB_USERNAME=root
DB_PASSWORD=
Now we will create a model using command: php artisan make:model Project -m (this will create an migration script):

D:\all-my-php-projects\ReactJS\ReactJSLaravelTutorial>php artisan make:model Project -m
Model created successfully.
Created Migration: 2019_03_03_153423_create_projects_table

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    protected $fillable = ['name', 'description'];
}

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProjectsTable extends Migration
{
    public function up()
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('description');
            $table->boolean('is_completed')->default(0);
            $table->timestamps();
        });
    }

    public function down()
    {
        
    }
}

And execute command php artisan migrate, this will create/modify table as needed.
We’ll start by defining the API endpoints. Open routes/api.php and replace it content with the code below:

<?php
Route::get('projects', 'ProjectController@index');
Route::post('projects', 'ProjectController@store');
Route::get('projects/{id}', 'ProjectController@show');
Route::put('projects/{project}', 'ProjectController@markAsCompleted');
Now we will create controller using command: php artisan make:controller ProjectController

<?php
namespace App\Http\Controllers;

use App\Project;
use Illuminate\Http\Request;

class ProjectController extends Controller
{
    public function index()
    {
        $projects = Project::where('is_completed', false)
            ->orderBy('created_at', 'desc')
            ->withCount(['tasks' => function ($query) {
                $query->where('is_completed', false);
            }])
            ->get();

        return $projects->toJson();
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required',
            'description' => 'required',
        ]);

        $project = Project::create([
            'name' => $validatedData['name'],
            'description' => $validatedData['description'],
        ]);

        return response()->json('Project created!');
    }

    public function show($id)
    {
        $project = Project::with(['tasks' => function ($query) {
            $query->where('is_completed', false);
        }])->find($id);

        return $project->toJson();
    }

    public function markAsCompleted(Project $project)
    {
        $project->is_completed = true;
        $project->update();

        return response()->json('Project updated!');
    }
}
We’ll be using React Router to handle routing in our application. For this, we need to render a single view file for all our application routes. Open routes/web.php and replace it content with the code below:

Route::view('/{path?}', 'app');
Next, let’s create the app.blade.php view file. We’ll create this file directly within the resources/views directory, then paste the following code in it:

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Project Management</title>
    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app"></div>

<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
The App component will serve as the base for our React components. Let’s rename the default Example component to App and replace it content with the following code:
// resources/js/components/App.js

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Header from './Header'
import ProjectsList from './ProjectsList'

class App extends Component {
    render () {
        return (
            <BrowserRouter>
                <div>
                    <Header />
                    <Switch>
                        <Route exact path='/' component={ProjectsList} />
                    </Switch>
                </div>
            </BrowserRouter>
        )
    }
}

ReactDOM.render(<App />, document.getElementById('app'));


Now install react router using command: npm install react-router-dom

update resources/assets/js/app.js as below:

require('./bootstrap');
require('./components/App');
Create a new Header.js file within the resources/js/components directory and paste the code below in it:

import React from 'react'
import { Link } from 'react-router-dom'

const Header = () => (
    <nav className='navbar navbar-expand-md navbar-light navbar-laravel'>
        <div className='container'>
            <Link className='navbar-brand' to='/'>Project Management</Link>
        </div>
    </nav>
);

export default Header
Create a new ProjectsList.js file within the resources/js/components directory and paste the code below in it:

import axios from 'axios'
import React, { Component } from 'react'
import { Link } from 'react-router-dom'

class ProjectsList extends Component {
    constructor () {
        super();
        this.state = {
            projects: []
        }
    }

    componentDidMount () {
        axios.get('/api/projects').then( response => {
            this.setState({
                projects: response.data
            })
        })
    }

    render () {
        const { projects } = this.state;
        return (
            <div className='container py-4'>
                <div className='row justify-content-center'>
                    <div className='col-md-8'>
                        <div className='card'>
                            <div className='card-header'>All projects</div>
                            <div className='card-body'>
                                <Link className='btn btn-primary btn-sm mb-3' to='/create'>
                                    Create new project
                                </Link>
                                <ul className='list-group list-group-flush'>
                                    {projects.map(project => (
                                        <Link
                                            className='list-group-item list-group-item-action d-flex justify-content-between align-items-center'
                                            to={`/${project.id}`}
                                            key={project.id}>
                                            {project.name}
                                            <span className='badge badge-primary badge-pill'>{project.tasks_count}</span>
                                        </Link>
                                    ))}
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default ProjectsList
This is the basic structure for ReactJS with Laravel. Execute php artisan serve to start server.
Some sample screen shots:



Run command npm run dev (for windows user, run command as an administrator) to compile ReactJS code once you made some changes.

Below is GitHub link of this project:

https://github.com/pritomkucse/reactjs-with-laravel-6.X

After download source from GitHub run command composer install to install laravel dependencies, then run php artisan migrate for database migration (but make sure you configure database in .env file) and then run npm install to install ReactJS dependencies. Finally run npm run dev to package ReactJS and then browser your project directory. That's all.


Sample .env File
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:PuBBf9PHnf4RkJokRNDMeTDY6SWWr8s2TilF9E3b4Fs=
APP_DEBUG=true
APP_URL=http://react-with-laravel.com
APP_PATH=/

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db-laravel1
DB_USERNAME=root
DB_PASSWORD=1234

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

Sample Virtual Host File

<VirtualHost react-with-laravel.com:80>
    DocumentRoot "C:\Users\PRITOM\Desktop\MINE\reactjs-with-laravel-6.X\public"
    ServerName react-with-laravel.com
    ErrorLog "logs/react-with-laravel.com-error.log"
    CustomLog "logs/react-with-laravel.com-access.log" combined
    <Directory "C:\Users\PRITOM\Desktop\MINE\reactjs-with-laravel-6.X">
        Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
            Require all granted
    </Directory>
</VirtualHost>

Sunday, March 3, 2019

Install ReactJS on Windows using NPM with help of NODEJS

First needs to install NodeJS, for windows users, go to https://nodejs.org/en/ and download your suitable installer and install if not alredy installed.
After installation completed go to your installation directory (for me its C:\Program Files\nodejs\node_modules) and check there is a folder named "npm", if exists open a command prompt (WINDOWS_BUTTON+CMD) and type command "npm -v" to see if nodejs installed properly.

Now time to install React from Terminal: npm install -g create-react-app, it will take some time to complete.

If successful, you should be able to get version: create-react-app --version
Now time to create a project: create-react-app react_app1, after create project navigate to project directory using cd react_app1

Expected output in terminal (and should auto open browser to port 3000) on start project using command npm start:


Friday, March 1, 2019

How to install Laravel 5 with Xampp (Windows)

Requirements
  1. PHP >= 5.5.9
  2. OpenSSL PHP Extension
  3. PDO PHP Extension
  4. Mbstring PHP Extension
  5. Tokenizer PHP Extension
Install Xampp
First of all, we need Xampp, so we can download it from the official page: Download Xampp
Install Composer
After you've downloaded and installed Xampp, we need to install Composer.
Composer is a PHP package manager that is integrated with Laravel Framework. In Windows we can install it easy going to the official page and download the installer. Composer Download page

Install Laravel Framework
We are prepared to install and configure a Laravel Framework. First of all, we have to navigate to htdocs folder to install it and run this following command:
composer create-project laravel/laravel laravel "5.1.*"
When it finishes, it will create following directory schema:

Now browse your laravel project into browser: