How To Make A Cmd Login Register Program
Past using Laravel Authentication
Stride ane: Create your project using this command:
composer create-project --prefer-dist laravel/laravel project-name
Step 2: Run these commands on the terminal:
composer require laravel/ui
php artisan ui vue --auth
npm install && npm run dev
Step 3: Create a database and set up the database configurations within .env file and
within config > database.php.
.env file:
DB_DATABASE=auth
DB_USERNAME=root
DB_PASSWORD=countersign
config>database.php:
Footstep four: Run the following command in last:
php artisan migrate
Y'all are all set to register the user and login.
By making our own Login and Registration Files using Laravel MVC Structure
As we know Laravel follows MVC structure, i.e. Model View Controller Structure.
VIEW: View contains HTML part of our application and separates our awarding logic from presentation logic.
CONTROLLER: In Controller, all our logical and business logical part is defined. The controller contains request handling logic inside a single function. From view Part, our data is sent to the controller and from the controller, we send our information to Model to save it to the database.
MODEL: Model is a course that represents the logical structure and human relationship of the underlying data table. In Laravel, each database tabular array has a corresponding Model that allows us to interact with that table. The model gives us the style to retrieve, insert, update, and delete information from the data tabular array.
Y'all need to create a Laravel Project first past using this command.
composer create-project --adopt-dist laravel/laravel project-proper noun
STEP 1: CREATE VIEW PAGES FOR REGISTRATION AND LOGIN
Create view pages for Registration Folio and Login Folio.
views>registration.bract.php
views>login.blade.php
Nosotros tin also create a layout file in which we can write common code that can exist used all over the application. We can extend the layout file code by extending the file in other view files by using directives.
@extends('layout')
layout.blade.php:
<html>
<head>
<title>Restaurant Website
</championship>
<style>
.content{
background-image:linear-slope(to right,#C9D6FF,#E2E2E2);
height:600px;
}
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://lawmaking.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="bearding"></script>
</head>
<body>
<header>
<nav form="navbar navbar-expand-lg navbar-low-cal" mode="background:#D76D77">
<a class="navbar-brand" href="/">RESTO</a>
<push button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-characterization="Toggle navigation">
<span class="navbar-toggler-icon"></bridge>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
@if(Session::get('user'))
<a class="nav-item nav-link" href="/list">List</a>
<a grade="nav-detail nav-link" href="/add">Add together</a>
@endif
<</div>
<div class="navbar-nav ml-automobile">
@if(Session::become('user'))
<a class="nav-detail nav-link" href="#">Welcome, {{Session::get('user')}}</a>
<a class="nav-particular nav-link" href="/logout">Logout</a>
@else
<a class="nav-item nav-link agile" href="/login">Login</a>
<a course="nav-item nav-link active" href="/register">Register</a>
@endif
</div>
</div>
</nav>
</header>
<div grade="content d-flex justify-content-center">
@yield('content')
</div>
<footer class="container"></footer>
</trunk>
</html>
registration.blade.php:
@extends('layout')
@department('content')
<div class="col-sm-viii">
<h3>Register User</h3>
@if(Session::get('register_status'))
<div class="warning alarm-success alert-dismissible fade evidence" function="alarm">
{{Session::get('register_status')}}
<button type="push" class="close" information-dismiss="alarm" aria-label="Close">
<bridge aria-hidden="true">×</bridge>
</push>
</div>
@endif
<form action="registerUser" method="post" return="false">
<div class="form-group">
<characterization>Name
<input type="text" name="name" value="{{ old('proper noun') }}" form="class-command" placeholder="Enter Name" required>
</div>
@error('name')
<div grade="alert alert-danger">{{ $message }}</div>
@enderror
@csrf
<div class="form-group">
<label>Electronic mail
<input blazon="text" name="email" value="{{ former('e-mail') }}" class="form-control" placeholder="Enter Email" required>
</div>
@error('email')
<div class="alert warning-danger">{{ $message }}</div>
@enderror
<div form="form-group">
<label>Password
<input type="countersign" proper noun="password" value="{{ sometime('password') }}" course="class-command" placeholder="Enter Password" required>
</div>
@fault('password')
<div class="alert warning-danger">{{ $message }}</div>
@enderror
<div class="form-grouping">
<label>Confirm Password
<input type="password" proper name="confirm_password" value="{{ former('confirm_password') }}" course="form-command" placeholder="Confirm Password" required>
</div>
@error('confirm_password')
<div class="alert alert-danger">{{ $bulletin }}</div>
@enderror
<div class="class-grouping">
<label>Mobile</label>
<input type="number" name="mobile" value="{{ former('mobile') }}" grade="form-command" placeholder="Enter Mobile Number" required>
</div>
@mistake('mobile')
<div course="alarm warning-danger">{{ $bulletin }}</div>
@enderror
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
@endsection
login.blade.php:
@extends('layout')
@department('content')
<div class="col-sm-8">
<h3>Login User</h3>
@if(Session::get('error'))
<div class="alert alarm-danger alert-dismissible fade show" role="alert">
{{Session::get('error')}}
<push blazon="button" class="close" data-dismiss="alert" aria-label="Shut">
<bridge aria-hidden="true">×</span>
</button>
</div>
@endif
<course activeness="loginUser" method="postal service">
@csrf
<div form="class-grouping">
<label>Email</label>
<input type="email" name="e-mail" value="{{ old('email') }}" form="grade-control" placeholder="Enter Electronic mail" required>
</div>
@mistake('email')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
<div class="form-group">
<label>Password</characterization>
<input type="password" name="countersign" class="form-command" placeholder="Enter Password" required>
</div>
@fault('countersign')
<div class="warning warning-danger">{{ $message }}</div>
@enderror
<push blazon="submit" grade="btn btn-primary">Submit</button>
</form>
</div>
@endsection
STEP 2: CREATE ROUTES FOR VIEW FILES:
To access the Registration and Login view files, nosotros need to create routes in web.php file. Open routes > web.php
Route::view('annals','register');
Route::view('login','login');
Pace 3: CREATE CONTROLLER:
We need to create a Controller to handle our form data. From View Files, When we submit our class data, it goes to Controller. Nosotros can brand the controller by using the following command:
Php artisan brand:controller RestoController
Yous will find your controller under App > http > Controller > RestoController
STEP iv: CREATE ROUTES FOR CONTROLLER:
Set routes for controller in web.php
Route::post('registerUser','RestoController@registerUser');
Road::mail('loginUser','RestoController@login');
Create the functions registerUser() and login() to handle the data. For Instance, role registerUser() will handle registration information. In this function, nosotros will validate the user's data and so laissez passer that data to the data table to store it in the database using Model. So we need to create a Model for that particular data table in which nosotros want to store our user's data.
STEP v: CREATE MODEL:
We tin create a model past using the following command:
Php artisan make:model User
The table proper name should ever be in plural and the corresponding model proper noun should be singular. Import Model in your Controller. After Validating, Send your information to the information table using Model.
Register:
- You lot demand to salve your password in encrypted class. We can not salvage passwords directly into information tables as submitted by Users.
$encrypted_password = crypt::encrypt($information['password']); - If User is registered successfully, Set a flash session with a message that User has been registered successfully and redirect to the same folio. But if at that place is an error, and then show that error message on view Folio. We use flash sessions for this because they go expired once the folio is refreshed.
$req->session()->wink('register_status','User has been registered successfully');
return redirect('/register'); - The 1 of import matter we need to bank check is that the email id using which once a user has been registered should never exist able to register again with the same e-mail Id.
function registerUser(Request $req){
$validateData = $req->validate([
'name' => 'required|regex:/^[a-z A-Z]+$/u',
'email' => 'required|email',
'countersign' => 'required|min:vi|max:12',
'confirm_password' => 'required|same:password',
'mobile' => 'numeric|required|digits:10'
]);$result = DB::table('users')
->where('email',$req->input('email'))
->get();$res = json_decode($result,true);
print_r($res);if(sizeof($res)==0){
$information = $req->input();
$user = new User;
$user->proper noun = $data['name'];
$user->e-mail = $data['electronic mail'];
$encrypted_password = crypt::encrypt($data['password']);
$user->password = $encrypted_password;
$user->mobile = $information['mobile'];
$user->save();
$req->session()->flash('register_status','User has been registered successfully');
return redirect('/register');
}
else{
$req->session()->flash('register_status','This Email already exists.');
return redirect('/register');
}
}
LOGIN:
- Afterwards done with the Registration, We can log in. Login will also follow the same process.
- If the user logins with the email id which has been registered, he will be logged in successfully and be able to access the Dwelling house route and another routes.
- While login, we volition check whether this electronic mail id is existing in our information table or not, If not then we will tell the user to register offset using flash sessions. And if email Id exists, we demand to friction match the password. But how will nosotros lucifer the password?
Because the user while login is giving united states a unproblematic password. But the one which we saved during registration is an encrypted countersign. So how will we match it? - We can match it. We need to go the encrypted countersign of the corresponding email id from the data table and need to decrypt information technology using the decrypt function of crypt course. Later on decrypting, We can match both the passwords. If countersign matches, User tin be logged in otherwise show Password Mismatch Error.
office login(Request $req){
$validatedData = $req->validate([
'email' => 'required|electronic mail',
'countersign' => 'required'
]);$result = DB::tabular array('users')
->where('electronic mail',$req->input('email'))
->get();$res = json_decode($result,true);
print_r($res);if(sizeof($res)==0){
$req->session()->flash('error','Email Id does not be. Please register yourself beginning');
echo "Email Id Does not Be.";
return redirect('login');
}
else{
echo "Hello";
$encrypted_password = $result[0]->countersign;
$decrypted_password = crypt::decrypt($encrypted_password);
if($decrypted_password==$req->input('password')){
echo "You lot are logged in Successfully";
$req->session()->put('user',$result[0]->proper noun);
render redirect('/');
}
else{
$req->session()->flash('error','Password Wrong!!!');
echo "Email Id Does not Exist.";
return redirect('login');
}
}
}
Annotation:
Now one more than important thing to accept intendance of authenticity is that User should not exist able to access routes directly from the browser without being logged in.
For that, we can utilize Middleware.
STEP six: MIDDLEWARE
php artisan make:middleware customAuth
App > http > middleware > customAuth
In this Middleware, We can set some conditions that if the session is not prepare which means if the user is non logged in, he should not exist able to admission the home route. If he tries to admission information technology, he should be redirected to the login folio.
<?php
namespace App\Http\Middleware;
employ Closure;
use Session;
form customAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Asking $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $side by side)
{
$path = $request->path();
if($path=="login" && Session::go('user')){
render redirect('/');
}
else if(($path!="login" && !Session::get('user')) && ($path!="annals" && !Session::get('user'))){
return redirect('/login');
}
return $adjacent($asking);
}
}
Register Your Middleware:
App > http > kernel.php
In this kernel.php, We can add our middleware in any middleware(i.due east. Global, grouped, or Individual) and can name it. Now nosotros will employ that middleware proper name that we have set in Kernel.php on routes. I have added customAuth middleware equally customAuth in middlewareGroups.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::form,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::grade,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::grade,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:sixty,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'customAuth' => [
\App\Http\Middleware\customAuth::grade
] ];
Apply Middleware:
Utilise the middleware on the routes you desire to apply in web.php file.
Spider web.php:
Route::grouping(['middleware'=>'customAuth'],role(){
Road::get('/listing','RestoController@listing');
Route::view('/add','add');
Road::post('addResto','RestoController@addResto');
Route::view('register','register');
Road::view('login','login');
Road::get('logout','RestoController@logout');
});
Source: https://studysection.com/blog/user-registration-and-login-in-laravel/
Posted by: acrescorser.blogspot.com

0 Response to "How To Make A Cmd Login Register Program"
Post a Comment