How to develop custom login by auth middleware using laravel - laravel

I want to make a custom login system by auth middleware.
I don't have an idea how to do that.
controller
public function dologin(Request $request)
{
$request->validate([
'username' => 'required',
'password' => 'required'
]);
$username = $request->username;
$password = $request->password;
if (Auth::attempt(['username' => $username, 'password' => $password])) {
}
}
Blade view
<form action="{{route('login.action')}}">
<br>
<div class="form-row">
<div class="col">
<label>USERNAME</label>
<input type="text" class="form-control" placeholder="Enter Username" name="username">
</div>
</div>
<!--form-row-->
<br>
<div class="form-row">
<div class="col">
<label>PASSWORD</label>
<input type="password" class="form-control" placeholder="Enter password" name="password">
</div>
</div>
<!--form-row-->
<br>
<div class="form-group">
<input type="submit" name="btnsubmit" class="btn btn-success col-md-3" id="signup-btn" value="Login">
</div>
</form>
Route
// Login
Route::get('/login', 'LoginController#create')->name('login');
Route::get('/login/action', 'LoginController#dologin')->name('login.action');

Create your LoginController by runing this command in terminal:
php artisan make:controller LoginController
Then find your newly created controller under App\Http\Controllers\ and add a the use of Auth at the top of your controller
use Illuminate\Support\Facades\Auth;
Then add your dologin function to the controller and you're ready to go.

Related

Laravel : How to create custom Register

I have 2 register and login form. The one is used to user and others is used to admin role.
In user role, I using from laravel authentication, is good and work well.
But, the problem is when I create custom register from admin role, its can't work well.
It can't store to database, when I check using echo function, it's not print anything just refresh the page.
Could you help me, what is wrong ???
this is my route
Route::get('/adminregister', 'Auth\LoginController#formreg')->name('admin-reg');
this is my controller
namespace App\Http\Controllers\Admin\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class AregisterController extends Controller
{
use RegistersUsers;
public function __construct()
{
// $this->middleware('guest');
}
public function create(Request $request)
{
$this->validate(request(),[
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
if ($request('confirmpassword') == $request('password')){
$user = User::create(request(['name','email' ,'password','is_admin' => True, ]));
// return redirect()->route('admin-login')->with('status', 'Successfully create account');;
}
else {
return redirect()->route('admin-reg')->with('status', 'Confirm Password not match');;
}
}
}
In this controller, fisrt I want to check the password will confirmation password then store it to database.
this is my view page
<form action ="{{ route('user-create') }}" method="POST" enctype="multipart/form-data" >
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row mb-3">
<div class="col-md-12">
<div class="form-floating mb-2 mb-md-0">
<input class="form-control" id="inputFirstName" type="text" placeholder="Enter your first name" name="name" />
<label for="inputFirstName">Name </label>
</div>
</div>
</div>
<div class="form-floating mb-3">
<input class="form-control" id="inputEmail" type="email" placeholder="name#example.com" name="email"/>
<label for="inputEmail">Email address</label>
</div>
<div class="row mb-3">
<div class="col-md-6">
<div class="form-floating mb-3 mb-md-0">
<input class="form-control" id="inputPassword" type="password" placeholder="Create a password" name="password" />
<label for="inputPassword">Password</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating mb-3 mb-md-0">
<input class="form-control" id="inputPasswordConfirm" type="password" placeholder="Confirm password" name="confirmpassword" />
<label for="inputPasswordConfirm">Confirm Password</label>
</div>
</div>
</div>
<div class="mt-4 mb-0">
<div class="d-grid"><button type="submit" class="btn btn-primary">Create account</button></div>
</div>
</form>
Do you have any suggestion of how to fix it? It cant store anything in database, and when I check it using " echo " there is nothing :)
Thank you
The confirmed rule is looking for a field name {field}_confirmation. So if you are trying to confirm the 'password' input it would be looking for a field named password_confirmation. So that input in the form needs to be changed to the name password_confirmation.
You won't need to compare the 2 password fields that are submitted since the confirmed rule has done that for you already (that is what it is for; to confirm that they match).
The Request class is not callable, $request(...). That will throw an error since it isn't callable (there is no __invoke method defined on it to make it callable).
To create the User you can get the fields you need easily with the only method:
$request->only('name', 'email', 'password')
You can add your is_admin value to the array returned from the only call:
User::create($request->only('name', 'email', 'password') + ['is_admin' => true])
You will have to make sure that the is_admin field is "fillable" on the Model.
In general you don't need to be calling request() any where in this method since you have a Request instance injected as $request already.
Also, your form isn't handling a file upload so you don't need enctype="multipart/form-data".

Login Form Not Working Correctly it keeps redirecting to the same page when the users try to access their account

I have an issue with my login form where when I press the login button, the web app just redirects me to the same page. This is first time I'm making a custom login form so it's a little complex for me as I used laravel/ui in my first project. I think the problem is that the model cannot directly access the users table that's in the db. I've linked the user model to the controller but that doesn't help. If anyone can take their time to show me how to connect the login form to the users table or tell me what's wrong with my code. Here's the code that I've written so far for the login.
Login Form
<form method="post" action="/login" enctype="multipart/form-data">
#csrf
<div class="col-md-12 mt-md-0 mt-3">
<label for="email" id="email">Email</label>
<input type="email" name="email" value="{{ old('email') }}" class="form-control" placeholder="E-mail" required>
#error('email')<p class="text-danger"><small>{{$message}}</small></p> #enderror
</div>
<div class="col-md-12 mt-md-0 mt-3">
<label for="password" id="password">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password"required>
#error('password')<p class="text-danger"><small>{{$message}}</small></p> #enderror
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary mb-4 w-50 py-2 fw-bold" >Login</button>
</div>
</form>
Routes
Route::get('login', [SessionsController::class, 'create'])->middleware('guest');
Route::post('login', [SessionsController::class, 'store'])->middleware('guest');
SessionsController
public function store()
{
$attributes = request()->validate([
'email' => 'required|email',
'password' => 'required'
]);
if (! auth()->attempt($attributes)) {
throw ValidationException::withMessages([
'email' => 'Your provided credentials could not be verified.'
]);
}
session()->regenerate();
return redirect('/')->with('success', 'Welcome');
}
I think the problem is that this form is not retrieving the data from the db that's being stored when the user registers an account.

How to get session mobile in laravel

I want to after registered a user name, age, mobile and ... get the session of mobile because in next page, I want to get mobile in input hidden.
Attention: I did not do session at all.
I think it's like this:
RegisterController.php
public function register(Request $request, User $user)
{
$code = rand(10000,99999);
session->get('mobile')
$user = \App\User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'gender' => $request->gender,
'mobile' => $request->mobile,
'code' => $code,
.
.
.
return redirect()->route('code')->with('mobile', $request->mobile);
}
It redirect to this page.
Code
code.blade.php
<form action="{{ route('send') }}" method="post">
{{ csrf_field() }}
<input type="hidden" class="form-control" value="{{ session->mobile }}" name="mobile" id="mobile">
<div class="form-group">
<label for="code">کد</label>
<input type="text" class="form-control" name="code" id="code">
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger" id="btn-ok">OK</button>
</div>
</form>
use Illuminate\Support\Facades\Session;
For saving in session use
Session::put('mobile', $request->mobile);
then retrieve it using
Session::get('mobile');

Laravel, adding data to database after verifying ReCaptcha

I'm using ReCaptcha in my Laravel project, done it with this
tutorial.
I need to create a page where user can post his message after checking captcha.
I have created a modal dialog where user can fill in data like this :
<form class="form-horizontal" action="" method="post">
<div class="form-group error">
<label for="messageName" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Your name" value=""
ng-model="message.name" ng-required="true">
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageEmail" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control has-error" id="email" name="email" placeholder="E-mail" value=""
ng-model="message.email" ng-required="true">
<span class="help-inline"
ng-show="GBM.email.$invalid && GBM.email.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageLink" class="col-sm-3 control-label">Web</label>
<div class="col-sm-9">
<input class="form-control" rows="3" class="form-control has-error" id="web" name="web" placeholder="Link for your web" value="" ng-model="message.web" ng-required="false" >
</div>
</div>
<div class="form-group error">
<label for="messageText" class="col-sm-3 control-label">Comment</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" class="form-control has-error" id="comment" name="comment" placeholder="Your comment" value="" ng-model="message.text" ng-required="true" ></textarea>
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
{!! csrf_field() !!}
<!-- recaptcha -->
{{Request::is('contactd')}}
<div class="form-group">
<div class="col-md-9">
<div class="g-recaptcha" data-sitekey="{{env('GOOGLE_RECAPTCHA_KEY')}}"></div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-9 control-label"></label>
<div class="col-md-9">
<button type="submit" name="send" class="btn btn-primary btn-lg btn-block">Add new message <span class="fa fa-paper-plane-o"></span></button>
</div>
</div>
</form>
For a route I got it like this:Route::post('contact','ContactController#store');
And here is the problem, in my controller i got this code to verify captcha:
public function store(ReCaptchataTestFormRequest $request){
return "Captcha done right! ";}
And this code to save data to database
public function store(Request $request)
{
$this->validate($request, [ 'name' => 'required|max:255' ]);
$this->validate($request, [ 'email' => 'required | email' ]);
$this->validate($request, [ 'comment' => 'required' ]);
$ip = $_SERVER['REMOTE_ADDR'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$guestbook = Guest_books::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'web' => $request->input('web'),
'comment' => $request->input('comment'),
'ip' => $ip,
'browser' => $browser
]);
return $guestbook;
}
So the question is: What to write in Controller for project to verify Captcha and then post it to database?
The tutorial you've followed teaches you how to create a custom validation rule which you can then use when validating requests, either through a Form Request or directly in your controller.
The mistake you've made in your controller is that you've called validate multiple times, instead you should pass it an array containing all of your rules, including your recaptcha rule, e.g:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email',
'comment' => 'required',
'g-recaptcha-response' => 'required|recaptcha',
]);
// ...
}
Additionally, you should note that the store method should always return a redirect.

ReflectionException in Route.php line 280: Method App\Http\Controllers\UserController::Signup() does not exist

I am a new programmer on laravel. I am currently using laravel 5.2. I ran into this error while i was trying to input data into a form i created as welcome.blade.php. I have check the route and it seems very okay. I dont what i may be doing wrong. This is problem display
ReflectionException in Route.php line 280:
Method App\Http\Controllers\UserController::Signup() does not exist
UserController
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function postSignUp(Request $request)
{
$email = $request['email'];
$first_name = $request['first_name'];
$password = bcrypt($request['password']);
$user = new User();
$user->email = $email;
$user->first_name = $first_name;
$user->password = $password;
$user->save();
return redirect()->back();
}
public function postSignIn(Request $request)
{
}
}
Routes
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('welcome');
});
Route::post('/signup', [
'uses' => 'UserController#Signup',
'as' => 'signup',
]);
});
welcome.blade.php
#extends('layouts.master')
#section('title')
Welcome!
#endsection
#section('content')
<div class="row">
<div class="col-md-6">
<h2>Sign Up</h2>
<form action="{{route('signup')}}" method="post">
<div class="form-group">
<label for="email">Your Email</label>
<input class="form-control" type="text" name="email" id="email">
</div>
<div class="form-group">
<label for="first_name">Your First Name</label>
<input class="form-control" type="text" name="first_name" id="first_name">
</div>
<div class="form-group">
<label for="password">Your Password</label>
<input class="form-control" type="text" name="password" id="password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
</form>
</div>
<div class="col-md-6">
<h2>Sign In</h2>
<form action="#" method="post">
<div class="form-group">
<label for="email">Your Email</label>
<input class="form-control" type="text" name="email" id="email"></div>
<div class="form-group">
<label for="password">Your Password</label>
<input class="form-control" type="text" name="password" id="password"></div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
#endsection
You're using diffrent function name according to route, both will be same.
Replace your function name with this:-
postSignUp to SignUp
Thanks for your contribution as suggested i change the postSignUp to SignUp in the userController
public function postSignUp(Request $request)
change to
public function SignUp(Request $request)
also in the route I change the
'uses' => 'UserController#Signup',
change to
'uses' => 'UserController#SignUp',

Resources