LaravelLaravel 8Reactjs

Reactjs Laravel 8 AUTH User Login Working Example

Reactjs Laravel 8 AUTH User Login Working Example

Hello guy’s welcome back to my blog. Today in this blog post, I am going to tell you, Reactjs Laravel 8 AUTH User Login Working Example.

Guy’s in this post we will do below things:

  1. Reactjs Laravel 8 user login functionality.
  2. Reactjs add sweetalert2 popup for success and error messages which will come from laravel 8 backend.
  3. React js Bootstrap 5 working.

Very first please check the working video:

User Login Working Video

Guy’s for setup laravel 8 auth user login and register backend process please check below links and after it process with this post:

  1. Laravel8 create user login register pages tutorial.
  2. Laravel8 create database settings to save user data in database.
  3. Reactjs Laravel8 auth user registration

Reactjs Laravel 8 AUTH User Login Working Example
Reactjs Laravel 8 AUTH User Login Working Example
Wrong user details validation popup
Wrong user details validation popup

Friends now I proceed onwards and here is the working code snippet and please use this carefully to avoid the mistakes:

1. Firstly friends we need fresh reactjs setup and for that we need to run below commands into our terminal and also w should have latest node version installed on our system:

npx create-react-app reactlaravel

cd reactlaravel

npm start // run the project

2. Now you need to run below commands to get axios, bootstrap and sweetalert module to make reactjs app looks good:

npm install sweetalert2-react

npm install bootstrap --save

npm install axios --save

npm start

3. Finally friends we need to add below code into our src/App.js file to get final output on web browser:

import React from 'react';
import './App.css';

//bootstrap
import 'bootstrap/dist/css/bootstrap.min.css';

//Include Sweetalert
import Swal from 'sweetalert2'

//axios for api request
import axios from 'axios';

class App extends React.Component {
  constructor(props)
    {
      super(props);
      this.addFormData = this.addFormData.bind(this);
    }
  //Form Submission
  addFormData(evt)
    {
      evt.preventDefault();
      const fd = new FormData();
      fd.append('email', this.refs.myEmail.value);
      fd.append('password', this.refs.password.value);
      
      //call api
      axios.post('http://127.0.0.1:8000/api/login', fd
      ).then(res=>
      {
      //Success alert
      if(res["data"]["status"] === "error")
      {
        Swal.fire({
          title: 'OPPS',
          text:   "Error,
          type: 'warning',
        
      });
      }
      else
      {
        Swal.fire({
        title: 'WOW',
        text:   "You have been logged-in successfully",
        type: 'success',

        });
    }
    this.myFormRef.reset();
    }
    );
    }
 
  render() {
   
    return (
    
      <div className="maincontainer">
        
        
        <div className="container p-5">
        <h1 className="text-center mb-5">Jassa therichpost</h1>
        <form ref={(el) => this.myFormRef = el}>
        <div class="mb-3">
          <label for="exampleFormControlInput2" class="form-label">Enter Email</label>
          <input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Email" ref="myEmail" />
        </div>
        <div class="mb-3">
          <label for="exampleFormControlInput3" class="form-label">Enter Password</label>
          <input type="password" name="password" class="form-control" id="exampleInputPass1" aria-describedby="passHelp" placeholder="Enter Password" ref="password" />
        </div>
        <button type="submit" className="btn btn-primary" onClick={this.addFormData}>Submit</button>
      </form>

       
            
      </div>

     
      </div>
      
)
};
}

export default App;

Laravel 8 api and controller functions:

1. Now we need to create new folder ‘API’ inside app/Http/Controllers folder and after that, we need to create AuthController.php file inside app/Http/Controllers/API folder and below code into it:

<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use Illuminate\Support\Facades\Auth; 
use App\Models\User; 
use Validator;
use Illuminate\Support\Str;
class AuthController extends Controller 
{
  
   private $apiToken;
   public function __construct()
    {
    $this->apiToken = uniqid(base64_encode(Str::random(40)));
    }
  /** 
   * 
   * @return \Illuminate\Http\Response 
   */ 
  

  public function login(Request $request){ 
    //User check
    if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
      $user = Auth::user(); 
    //Setting login response 
    $success['token'] = $this->apiToken;
    $success['name'] =  $user->name;
      return response()->json([
        'status' => 'success',
        'data' => $success
      ]); 
    } else { 
      return response()->json([
        'status' => 'error',
        'data' => 'Unauthorized Access'
      ]); 
    } 
  }
}

2. Now we need to add below code inside routes/api.php:

...
Route::post('login', [App\Http\Controllers\API\AuthController::class, 'login'])->name('login');

Now guy’s we are done. In next post we will do Reactjs Laravel 8 ecommerce site.

Guy’s if you have any kind of query then please feel free and comment below.

Jassa

Thanks

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11, Angular12, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.