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

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.

Related

Form Won't Pass Value Pair In Get Request Url After Submission

I'm familiarizing myself with API's Get & Post Request in Laravel. I have a form where an admin can send Points to an external API. Unfortunately, in the documentation the request has to be a GET request and the data which is being submitted has to append to the url
ie: myurl.com/my-end-point?platform_id=value&auth=value...
The issue is, whenever i fill the form and submit the url remains the same:
ie: myurl.com/my-end-point?platform_id=platform_id&auth=auth...
It does not pass the data in the get request.
Controller
public function sendCpdPoints(Request $request)
{
$response = Http::asForm()->get('myurl.com/my-end-point', [
'platform_id' => 'platform_id',
'auth' => 'auth',
'cpd_id' => 'cpd_id',
'registration_number' => 'registration_number',
'certificate' => 'certificate',
]);
dd($response);
}
View (Blade)
<form action="{{url('admin/rewards/points/manual_update/dashboard/store/participants-points') }}" method="POST">
<div class="modal-body">
{{ csrf_field() }}
<div class="form-group">
<label>Platform Id</label>
<input type="text" name="platform_id" id='platform_id' class="form-control" value="123" readonly>
</div>
<div class="form-group">
<label>Authentication Key</label>
<input type="text" name="auth" id='auth' class="form-control" value="123456789" readonly>
</div>
<div class="form-group">
<label>Cpd Id</label>
<input type="text" name="cpd_id" id='cpd_id' class="form-control" placeholder=".ie 587">
</div>
<div class="form-group">
<label>Registration Number</label>
<input type="text" name="registration_number" id='registration_number' class="form-control" placeholder=".ie MDC/PA/RNXXXX">
</div>
<div class="form-group">
<label>Certificate Serial Number</label>
<input type="text" name="certificate" id='certificate' class="form-control" placeholder=".ie 2022-03/001">
</div>
<button type="send" class="btn btn-primary">Send</button>
</div>
</form>
Help is greatly appreciated. As i really want to get better.
You need to pass the value from the form . You can use $request-> from the request facade
You can try this
public function sendCpdPoints(Request $request)
{
$response = Http::asForm()->get('myurl.com/my-end-point', [
'platform_id' => $request->platform_id,
'auth' => $request->auth,
'cpd_id' => $request->cpd_id,
'registration_number' => $request->registration_number,
'certificate' => $request->certificate,
]);
dd($response);
}
Let me see if I understand. Does your backend that handles the request call an external API? If that's the case, the problem is that you're passing strings as an argument. To retrieve the form values try something like:
$request->auth or
$request->get('auth')
If this is not the case, and you simply want to get the form data in your backend, I advise you to do it with JS using AJAX. You can use Fetch or install an external lib like axios to do this.
NOTE: the type of your submit button is incorrect, change it to type="submit"
https://www.w3schools.com/tags/att_button_type.asp

How to develop custom login by auth middleware using 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.

laravel: form action isn't working in laravel-5.8

When i click on submit button to submit data then it says:
404|not found
route
Route::resource('contactform', 'ContactformController');
blade
<form class="leave-comment" action="{{ route('contactform.store') }}" method="POST">
<h4 class="m-text26 p-b-36 p-t-15">
Send us your message
</h4>
<div class="bo4 of-hidden size15 m-b-20">
<input class="sizefull s-text7 p-l-22 p-r-22" type="text" name="contact_name" placeholder="Full Name">
</div>
<div class="bo4 of-hidden size15 m-b-20">
<input class="sizefull s-text7 p-l-22 p-r-22" type="text" name="contact_email" placeholder="Email Address">
</div>
<textarea class="dis-block s-text7 size20 bo4 p-l-22 p-r-22 p-t-13 m-b-20" name="contact_message" placeholder="Message"></textarea>
<div class="w-size25">
<!-- Button -->
<button type="submit" class="flex-c-m size2 bg1 bo-rad-23 hov1 m-text3 trans-0-4">
Send
</button>
</div>
</form>
controller
public function store(Request $request)
{
$request->validate([
'contact_name' => 'required',
'contact_email' => 'required|email',
'contact_message' => 'required'
]);
// send email
Mail::to('test#test.com')->send(new ContactformMail());
}
Anytime you define an HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the #csrf Blade directive to generate the token field:
<form method="POST" action="/profile">
#csrf
...
</form>

How can show error message in failed login?

I make authentication system using the following command:
php artisan make:auth
It works fine. But when I try to customize the design and other stuff everything seems messy to me.i.e: When I try with wrong credential it then I can't show the message like: 'Invalid Username/password'. I inspect the all controller inside Auth folder but no detail code is there. My requirement is so simple: I just want to pass error message from controller to view and show it with my custom designed HTML template. Here is my login form:
#extends('layouts.login')
#section('content')
<div class="content">
<!-- BEGIN LOGIN FORM -->
<form class="login-form" method="POST" action="{{ route('login') }}">
#csrf
<h3 class="form-title">Login to your account</h3>
CUSTOM_ERROR_MESSAGE_IF_LOGIN_FAILED
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span>
Enter any username and password. </span>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">Username</label>
<div class="input-icon">
<i class="fa fa-user"></i>
<!-- <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username"/> -->
<input id="email" type="email" class="form-control placeholder-no-fix" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
</div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<div class="input-icon">
<i class="fa fa-lock"></i>
<!-- <input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password"/> -->
<input id="password" type="password" class="form-control placeholder-no-fix" name="password" required autocomplete="current-password">
</div>
</div>
<div class="form-actions">
<label class="checkbox">
<!-- <input type="checkbox" name="remember" value="1"/> -->
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
Remember me </label>
<button type="submit" class="btn blue pull-right">
Login <i class="m-icon-swapright m-icon-white"></i>
</button>
</div>
<div class="forget-password">
<h4>Forgot your password ?</h4>
<p>
no worries, click <a href="{{ route('password.request') }}" >
here </a>
to reset your password.
</p>
</div>
<div class="create-account">
<p>
Don't have an account yet ? <a href="javascript:;" id="register-btn">
Create an account </a>
</p>
</div>
</form>
<!-- END LOGIN FORM -->
</div>
#endsection
How can I show CUSTOM_ERROR_MESSAGE_IF_LOGIN_FAILED?
First of all, believe me, we all have been there where you are now. It is frustrating when learning a new framework and how does it work.
One word of advice is to go through documentation thoroughly, there is nothing which you can't find there when it comes to Laravel. Well at least, nothing basics which you frequently need.
Now about your problem, you said:
I just want to pass error message from controller to view and show it
with my custom designed HTML template.
So I am going to take a wild guess and say that you are handling the login process yourself instead of using build-in Laravel functionality.
In case I am wrong and you are using build in laravel login functionlity then all you need to do is following:
Case 1: When you are using build in Laravel Login functionality
#if ($errors->has('email'))
<span class="invalid-feedback">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
Laravel returns the errors with keys 'email' when putting wrong credentials and try to login so just print the message using $errors->first('email') wherver you want and style it however you feel like it.
Now, if I am right and you are using custom login method:
Case 2: When you are using custom Login functionality
In your controller, you can customize your messages like so:
$messages = [
'email.required' => 'Email is required!',
'password.required' => 'Password is required!'
];
$validatedData = $request->validate([
'email' => 'required|email',
'password' => 'required|string',
], $messages);
Of course, this is just an example, you can have various validation and respective custom messages. If you want to use inbuild error messages of validation then just don't provide messages array like so:
$validatedData = $request->validate([
'email' => 'required|email',
'password' => 'required|string',
]);
When you use validate() method on $request, if validation fails, Laravel by default returns a valid error response to the blade, this response will have keys same as your request variable name and value as the error message and you can access them easily, same as in Case 1:
#if ($errors->has('email'))
<span class="invalid-feedback">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
And you are set.
Ultimately, maybe from your controller you want to return some custom error also other than validation the use following case:
Case 3: When you are using custom Login functionality and want to return some custom error message other than validation
Inside your controller use withErrors() method:
return Redirect::back()->withErrors(
[
'email' => 'Snap! you are done!'
]
);
As you might have guessed, showing this error inside your view is exactly the same as before:
#if ($errors->has('email'))
<span class="invalid-feedback">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
I hope it helps
Happy coding :)
You can output your error messages using:
#if(count($errors) > 0)
#foreach( $errors->all() as $message )
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span>{{ $message }}</span>
</div>
#endforeach
#endif
And you if you have a custom route, you need to redirect to the login page from your controller and passing the errors:
$errors = ['ur errors'];
return redirect()->back()->withErrors($errors);
Well, once in time I hovered over the same problem but found out that the messages were there and the only mistake was that the element which contains the error message was hidden by display:none and changed it like so .invalid-feedback { display: inline-block !important; }
After that I was able to see all the error messages. further more, I also, in LoginController, overrode the method sendFailedLoginResponse in AuthenticatesUsers
`protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
'password' => [trans('auth.password')],
]);
}`

Storing registration data in database using laravel 5.4

Have been trying to create a user registration/login page following laracast video.
But when I try to register a user, it return to the same page without given any error as to why. I also noticed that the supplied info is not stored in the database.
Am so confused I don't know what am doing wrong you help will be really appreciated
Here is my view:
<div class="col-md-offset-1 col-md-8">
<h1 class="text-center ">Register</h1>
<form method="POST" action="register" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" email="email" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" required>
</div>
<div class="form-group">
<label for="password_confirmation">Password Confirmation</label>
<input type="password" class="form-control" name="password_confirmation" required>
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-reply"></i>Register</button>
</form>
</div>
This is my controller
public function create()
{
return view('registration.create');
}
public function store(Request $request)
{
//validate form
$this->validate(request(),[
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
//create and save user
$user = new User; //create new Post model object
$user->name = $request->name; //adding thing to the the Post object
$user->email = $request->email;
$user->password = $request->password;
//save user
$user->save(); //to save the new item into the DB
//$user = User::create(request(['name', 'email', 'password']));
//sign them in
auth()->login($user);
//redirect to the admin
return redirect('/admin');
}
While this is my route file:
Route::get('register', 'RegistrationController#create');
Route::post('register', 'RegistrationController#store');
Thanks a lot in advance
Check your form, there's an error in the email field. It says:
and should be:
<input type="email" class="form-control" name="email" required>
So, replace email="email" with name="email"
first you add this error block. so, you can find error easily.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Then, your mistake is in form action. please replace it to below code.
<form method="POST" action="{{ route('register') }}" enctype="multipart/form-data">

Resources