I'm using Laravel Breeze for authentication, and I'm facing a problem:
When user request a password reset link, I like to show him/her a success message, if we send email successfully. PasswordResetLinkController returns this:
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
When it goes back, it goes, for example, to home route. HomeController returns home.blade.php. When I try to display $status, which should be passed by PasswordResetLinkController, I got undefiened variable error. How can I get that message?
EDIT
PasswordResetLinkController.php
// This is the original store function came with Breeze.
// I did touch neither code nor the comments.
public function store(Request $request)
{
$request->validate([
'email' => 'required|email',
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
HomeController.php
public function index()
{
$baseData = $this->baseData();
$asset = $this->pickAssetRandom();
$publishings = $this->paginate($this->getPublishings, 12);
return view('pages.home', compact('publishings', 'baseData', 'asset'));
}
The $status is being set in the PasswordResetLinkController.
Specifically:
back()->with('status', __($status))
So, as you can see, it is returning the previous page and passing in status.
However, if $status == Password::RESET_LINK_SENT is false, then $status is not set, but the $errors['email'] is. You can see this on the ternary condition in your code.
Try:
dd($status == Password::REST_LINK_SENT);
before the return statement on the controller, if you get false then there will be no $status, and you will get the undefiened variable error.
You can account for this in your view:
#if ($status)
{{ $status }} // A link was sent
#endif
// no link sent and here are the errors.
#if ($errors->any())
#foreach ($errors->all() as $error)
{{ $error }}
#endforeach
#endif
Laravel docs on this: https://laravel.com/docs/8.x/passwords#resetting-the-password
Treat that status as a session and it will work
#if (session('status'))
<span class="alert alert-success">{{ session('status') ?? ''}} </span>
#endif
Related
When doing add activity inside store method, after passing validation I am calling a method that returns success or failure.
But on failure, I am not able to handle the code properly.
If I redirect, am not getting the old value.
So How do i return to create method with error message & old value both?
Any way to populate the $errors array?
Am new to Laravel. Thanks in advance
public function store(Request $request, AppMailer $mailer)
{
$validatedData=$request->validate([
.......
........
]);
$tracking_model = new Tracking;
$result = $tracking_model->add($request->all());
if ($result === true) {
return redirect('posts')->with('success', 'Created Successfully');
}
else{
$err_msgs = $result;
//what to do here ???????
// return redirect('posts/create')->with('error', $err_msgs);
}
}
try this
in the controller
return redirect('posts/create')->withInput()->withErrors($err_msgs);
and in view .blade
#if ($errors->any())
#foreach ($errors as $error)
...
#endforeach
#else
No tags
#endif
I need a help . Can u guide me How can i Show a message to blocked user that his account has been blocked . i m just rendering him to post page . but i want to show him some message that your account has been blocked or somthing like we do in validation messages . Please guide briefly .
public function login(Request $request)
{
$username= $request->username;
$user = User::where('username',$username)->first();
// return $user;
// return $user->id;
if($user != null){
$active = Activation::whereUserId($user->id)->first();
if($active->completed==0){
return redirect('/posts');
}
You need to use session. One way to do that:
return redirect('posts')->with('error', 'Your account is blocked');
And in a view after redirection:
#if (session('error'))
{{ session('error') }}
#endif
If you don't want to redirect the user, just pass a variable into the view:
return view('login.form', ['notActivated' => $active->completed === 0])
And in the view:
#if ($notActivated)
Your account is blocked
#endif
I am trying to make an registration form with laravel 5.5 and mysql but the problem is it wont submit to the database..
PageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class PageController extends Controller
{
public function main(){
if (!Auth::Check()) {
return view('auth.login');
}
return view('user.main');
}
public function register_check(Request $request){
$this->validate($request, [
'username' => 'required|min:2|max:12|unique:users',
'fname' => 'required|min:5|max:20',
'position' => 'required|not_in:0',
'password' => 'required|min:6|max:12',
'ConfirmPass' => 'required|same:password',
'contactnum' => 'required|min:2|max:12'
]);
$user = new User;
$user->username = $request['username'];
$user->fname = $request['fname'];
$user->position= $request['position'];
$user->password = bcrypt($request['password']);
$user->ConfirmPass = $request['ConfirmPass'];
$user->contactnum = $request['contactnum'];
$user->save();
}
}
route web.php
Route::get('/', [
'as'=>'index',
'uses'=> 'PageController#main'
]);
Route::get('/register', [
'as'=>'register',
'uses'=> 'PageController#register'
]);
Route::post('/register_check', [
'as'=>'register_check',
'uses'=>'PageController#register_check'
]);
Any help will be greatly appreciated. thank you in advance
I am guessing there is an error in validation and you are being redirected back to the form. You might not be checking for $errors in your form view hence you don't see what the error is.
Place this code in your form view file. To see if there are any validation errors.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
The best way to deal with such situation is to check the response of save() function like:
if( $user->save() )
{
// Success message here
}
else
{
// Failure message here
}
now you will gt to know whether the save is successful or not.
Say,i have two form in one page.I have included one error blade file bellow both of the form. Now when i make wrong in one form & submit it the error message is showing bellow the both form.Its normal.But my question is, how do i separate this two error message,how can i differentiate by giving them two different name?
Give this a try
return redirect()->back()->withErrors([
'form1.name' => 'name is required in Form 1',
'form1.email' => 'email is required in Form 1',
'form2.city' => 'city is required in form 2'
]);
in your view
#if($errors->any())
#foreach ($errors->get('form1.*') as $error) {
{{ $error }}
#endforeach
#endif
So you can group errors by form using array notation form.name and get all with $errors->get('form.*).
Read more about errors here: https://laravel.com/docs/5.4/validation#working-with-error-messages
If you're using Form Request Validation, you can change the errorBag property to get a unique array of errors for your view file.
In your Request file:
class MyFormRequest {
protected $errorBag = 'foobar';
public function rules() { // ... }
}
In your controller:
public function store(MyFormRequest $request) {
// Store entry.
}
Then in your view file:
#if ($errors->foobar->isNotEmpty())
// Work with the errors
#endif
You can use the named error bags.
$validator = Validator::make($request->all(), [
'field1' => 'required',
'field2' => 'required|digits:1',
]);
if ($validator->fails()) {
return back()
->withErrors($validator, 'form1error')
->withInput();
}
To print the error in blade file use-
#if(count($errors->form1error)>0)
<ul>
#foreach($errors->form1error->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
I am using laravel-4 auth component . I want to make a function which will change user password . I have my view as follows :
password - Text-box ;
new_password - Text-box;
confirm_new_password - Text-box
I also have checked manual for password reset , but in that doc(http://laravel.com/docs/security#password-reminders-and-reset) they are sending mail for password reset .
View is as follows :
#extends('layouts.main')
#section('title') Change Password
#stop
#section('content')
{{ Form::open(array('url'=>'users/user-password-change', 'class'=>'block small center login')) }}
<h3 class="">Change Password</h3>
<h6>Please change your password below.</h6>
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
{{ Form::password('password', array('class'=>'input-block-level', 'placeholder'=>'Old Password')) }}
{{ Form::password('new_password', array('class'=>'input-block-level', 'placeholder'=>'New Password')) }}
{{ Form::password('confirm_new_password', array('class'=>'input-block-level', 'placeholder'=>'Confirm New Password')) }}
{{ Form::submit('Register', array('class'=>'k-button'))}}
{{ Form::close() }}
#stop
Controller code is as follows :
public function postUserPasswordChange(){
$validator = Validator::make(Input::all(), User::$change_password_rules);
if($validator->passes()){
$user=new UserEventbot;
$user->password=Hash::make(Input::get('new_password'));
$user->save();
return Redirect::to('users/change-password');
}else {
return Redirect::to('users/change-password')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
}
}
Please help me on this , how to first match this password with database table users , and then the whole process .
Thank you .
To match current user password with password in database you can do something like this,
// retrieve the authenticated user
$user = Auth::user();
Retrieve the current password specified by the user inside the form,
$current_password = Input::get('current_password');
We can see if the current password has bee specified and check against the hashed password as follows,
if (strlen($current_password) > 0 && !Hash::check($current_password, $user->password)) {
return Redirect::to('/user/edit-profile')->withErrors('Please specify the good current password');
}
Important thing to note here is the function
Hash::check(CURRENT_PASSWORD_ENTERED_IN_FORM, HASHED_VERSION_OF_PASSWORD_STORED_IN_AUTH_USER)
Finally, if it's all good you can update the current user password inside Auth and in database as follows,
// authenticated user
$user = Auth::user();
$user->password = Hash::make($new_password);
// finally we save the authenticated user
$user->save();
Try the following:
public function postUserPasswordChange(){
$validator = Validator::make(Input::all(), User::$change_password_rules);
if($validator->passes()){
$user = UserEventbot::findOrFail(Auth::user()->id);
$user->password = Hash::make(Input::get('new_password'));
$user->save();
return Redirect::to('users/change-password');
}else {
return Redirect::to('users/change-password')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
}
}
this is my own solution, I have 3 inputs = old_password, password, password_confirmation, form with action=post.
Validator check requirements, hash checks if Old password matches
public function changePassword()
{
$user = Auth::user();
$rules = array(
'old_password' => 'required|alphaNum|between:6,16',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::action('UserController#show',$user->id)->withErrors($validator);
}
else
{
if (!Hash::check(Input::get('old_password'), $user->password))
{
return Redirect::action('UserController#show',$user->id)->withErrors('Your old password does not match');
}
else
{
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::action('UserController#show',$user->id)->withMessage("Password have been changed");
}
}
}
Please try the following changed
public function postUserPasswordChange(){
$validator = Validator::make(Input::all(), User::$change_password_rules);
if($validator->passes()){
$user = UserEventbot::findOrFail(Auth::user()->id);
if(Hash::check(Input::get('password'), $user->getAuthPassword())) {
$user->password = Hash::make(Input::get('new_password'));
$user->save();
return Redirect::to('users/change-password')->with('message','Your password has been changed');
}
}
return Redirect::to('users/change-password')->with('message', 'The following errors occurred')->withErrors($validator);
}
You should exclude withInput() in term of password.Hope this help