How to change password? - laravel

I want to edit form update only address, email and password. How to change password? The old password is important.
edit.blade.php
<form method="POST" action="{{ route('update') }}">
#csrf
{{ method_field('PATCH') }}
<div class="form-group row">
<label for="email" class="col-md-1 col-form-label text-md-right">{{ __('Email') }}</label>
<div class="col-md-5">
<input id="email" type="text" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') ? : user()->email }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-1 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-5">
<input id="password" type="text" class="form-control #error('password') is-invalid #enderror" name="password" value="{{ old('password') }}" required autocomplete="password" autofocus>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="address" class="col-md-1 col-form-label text-md-right">{{ __('Address') }}</label>
<div class="col-md-5">
<textarea id="address" type="text" class="form-control #error('address') is-invalid #enderror" name="address" required autocomplete="address" autofocus>{{ old('address') ? : user()->address }}</textarea>
#error('address')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-1">
<button type="submit" class="btn btn-block btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
Route
Route::post('update', 'Auth\RegisterController#sqlupdate')->name('update');
RegisterController
public function sqlupdate(Request $request)
{
Auth::user()->update([
'address' => $request['address'],
'email' => $request['email'],
]);
$hashedPassword = auth()->user()->password;
if (Hash::check($request->oldpassword, $hashedPassword)){
$user = User::findOrFail(Auth::id());
$user->password = Hash::make($request->password);
}
return redirect()->back();
}

Just read the below code carefully :-
/**
* Admin My profile : Password update.
*
* #param Request $request
* #param $id
* #return \Illuminate\Http\Response
*/
public function updatePassword(Request $request,$id = 0)
{
$validate = Validator::make($request->all(),[
'old_password' => 'required',
'password' => 'required|confirmed|min:8',
'password_confirmation' => 'required|min:8',
]);
$getUserData = Admin::where('id',$id)->first();
if($getUserData === null) {
return redirect()->back()->with([
'status' => 'warning',
'title' => 'Warning!!',
'message' => 'Invalid Admin ID.'
]);
}
$validate->after(function ($validate) use ($request,$getUserData,$id) {
if(!Hash::check($request->get('old_password'),$getUserData->password)){
$validate->errors()->add('old_password', 'Wrong old password');
}
});
if($validate->fails()){
return redirect()->back()->withErrors($validate)->withInput();
}
try{
$getUserData->update([
'password' => Hash::make($request->get('password'))
]);
return redirect()->back()->with([
'status' => 'success',
'title' => 'Success!!',
'message' => 'Admin password updated successfully.'
]);
}catch (Exception $e){
return redirect()->back()->with([
'status' => 'error',
'title' => 'Error!!',
'message' => $e->getMessage()
]);
}
}
With the above method you'll get the idea of how we update password, this is from one of my project i've created three field for that here is the screenshot of view :-
I hope this will help
Further more update here is the small snippet for update method
specially
$getOldPassword = User::where('id',$id)->first();
if($request->get('password') === null){
$password = $getOldPassword->password;
}else{
$password = Hash::make($request->get('password'));
}

Related

Cannot add data for second time but work for firs time, laravel add user

I'm trying to create a form to insert a user but the function doesn't work the second time, only the first. I got *rror after submitting it a second time.
302 found
UserController
class UserController extends Controller
{
// User
public function edit()
{
return view(
'pages.user.edit',
[
'user' => Auth::user(),
'title' => ''
]
);
}
public function create()
{
return view('pages.user.createUS', [
'levels' => Level::get(),
'perusahaans' => Perusahaan::get(),
'satkers' => Satker::get(),
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
public function store(Request $request)
{
// dd($validatedData);
$this->validate(request(), [
'name' => 'required',
'level_id' => 'required',
'satker_id' => 'required',
'username' => ['required', 'string', 'max:255', 'unique:users'],
'phonenumber' => ['required', 'unique:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
]);
$errors = $this->errors();
if ($this->fails()) {
return redirect('users/create')->withErrors($errors)->withInput()->with('err', true);
}
// dd($validatedData, $request);
$user = new User([
'name' => request('name'),
'username' => request('username'),
'email' => request('email'),
'phonenumber' => request('phonenumber'),
'level_id' => request('level_id'),
'satker_id' => request('satker_id'),
'remember_token' => Str::random(10)
]);
$user->password = md5(request('password'));
$user->save();
return redirect()->route('users.create')->with('success', 'User Berhasil Dibuat!');
}
/**
* Indicate that the model's email address should be unverified.
*
* #return static
*/
public function unverified()
{
return $this->state(function (array $attributes) {
return [
'email_verified_at' => null,
];
});
}
public function index()
{
$users = User::latest()->get();
$perusahaans = Perusahaan::get();
$satkers = Satker::latest()->get();
return view(
'pages.user.index',
[
'users' => $users,
'perusahaans' => $perusahaans,
'satkers' => $satkers,
'levels' => Level::get()
]
);
}
public function action(Request $request)
{
$pid = $request->post('pid');
$satkers = Satker::where('perusahaan_id', $pid)->latest()->get();
$html = '<option value="">Pilih Satuan Kerja</option>';
foreach ($satkers as $satker) {
$html .= '<option value="' . $satker->id . '">' . $satker->satker . '</option>';
}
echo $html;
// return response()->json(['html' => $html]);
}
// Setting Profile
public function show(User $user)
{
$details = DetailTransaksi::get();
$transaksis = Transaksi::latest()->get();
$tagihans = Tagihan::latest()->get();
$satkers = Satker::latest()->get();
// dd($tagihans->where('user_id', $user->id));
return view('pages.user.detail', [
'user' => $user,
'transaksis' => $transaksis,
'details' => $details,
'tagihans' => $tagihans,
]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$user = Auth::user();
// $file_name = $request->image->getClientOriginalName();
$rules = [
'name' => 'required',
'username' => 'required',
'satker_id' => 'required',
'email' => 'required',
'phonenumber' => 'required',
'level_id' => 'required',
];
if (
$request->email != $user->email
) {
$rules['email'] = 'required|unique:users';
}
$validatedData = $request->validate($rules);
$validatedData['id'] = auth()->user()->id;
User::where('id', $user->id)
->update($validatedData);
return redirect('/user')->with('success', 'Profile has been Updated');
}
}
Blade
<section id="produk-form-create" class="">
<h4 class="fw-bold py-3 mb-4">
<span class="text-muted fw-light">User /</span> Tambah Data User
</h4>
<div class="col-xxl">
<div class="card mb-4">
<div class="card-header d-flex align-items-center justify-content-between">
<h5 class="mb-0">Form Tambah Produk</h5>
</div>
<div class="card-body">
<form action="/users/store" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6 mb-3 text-start">
<label for="name" class="form-label">Nama User</label>
<input id="name" type="name" name="name" value="{{ old('name') }}"
class="form-control #error('name') is-invalid #enderror" required>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="username" class="form-label">Username</label>
<input id="username" type="text" name="username" value="{{ old('username') }}"
class="form-control #error('username') is-invalid #enderror" required>
#error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="email" class="form-label">Email</label>
<input id="email" name="email" value="{{ old('email') }}" type="text"
class="form-control #error('email') is-invalid #enderror" required>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="leveluser" class="form-label">Level User</label>
<select class="form-select #error('leveluser') is-invalid #enderror" id="leveluser"
name="level_id" required>
#foreach ($levels as $level)
<option value="{{ $level->id }}">{{ $level->level }}</option>
#endforeach
</select>
#error('level_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label class="form-label" for="phonenumber">Phone Number</label>
<div class="input-group input-group-merge">
<span class="input-group-text">ID (+62)</span>
<input type="text" id="phonenumber" name="phonenumber" class="form-control"
placeholder="" value="{{ old('phonenumber') }}" required>
#error('phonenumber')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6 mb-3 text-start">
<label for="perusahaan" class="form-label">Perusahaan</label>
<select class="form-select #error('perusahaan_id') is-invalid #enderror" id="perusahaan_id"
name="perusahaan_id" required>
#foreach ($perusahaans as $perusahaan)
<option value="{{ $perusahaan->id }}">{{ $perusahaan->nama_perusahaan }}
</option>
#endforeach
</select>
</div>
<input type="hidden" name="password" id="password" value="12345678">
<div class="col-md-6 mb-3 text-start">
<label for="password" class="form-label">Password</label>
<p>Password default untuk user adalah
<mark><strong
class="text-warning">"12345678"</strong></mark>
mohon arahkan kepada
user untuk mengganti password demi keamanan dan kenyamanan bersama.
</p>
</div>
<div class="col-md-6 mb-3 text-start">
<label for="satker_id" class="form-label">Satuan Kerja</label>
<select id="satker_id" name="satker_id"
class="form-select #error('satker') is-invalid #enderror" required>
#foreach ($satkers->where('perusahaan_id', 1) as $satker)
<option value="{{ $satker->id }}">
{{ $satker->satker }}
</option>
#endforeach
</select>
#error('satker_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row">
<div class="col-sm-4 ">
<button type="submit" class="btn btn-primary"><i class="fw-icons bx bx-send"></i>
Send
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
Routes
Route::get('users', [UserController::class, 'index'])->name('users')->middleware('userlevel');
Route::get('users/{user}/edit', [UserController::class, 'edit'])->name('users.edit')->middleware('userlevel');
Route::get('users/create', [UserController::class, 'create'])->name('users.create')->middleware('userlevel');
Route::post('/users/store', [UserController::class, 'store'])->name('users.store')->middleware('userlevel');
Route::delete('users/{user}/destroy', [UserController::class, 'destroy'])->name('users.destroy')->middleware('userlevel');
Route::put('users/{user}/update', [UserController::class, 'update'])->name('users.destroy')->middleware('userlevel');
Route::post('users/action', [UserController::class, 'action']);
Success in the first-time post but get 302 found in the second time. Please help me to solve this problem.

Reset password manually via answering the security questions without sending email - Laravel/auth

I am currently developing a simple Bookstore application with a few numbers of users on which sending emails are not needed because it will be implemented in local system so is there any way to customize laravel-auth for password reset function by adding a few security questions fields where user can reset his/her password without sending reset links via email.
Any kind of help will be highly appreciated.
here I tried the below code but id did not work
Code in web.php
Route::post('/main/checklogin', 'UserController#chekQuestions');
Code in userContoller
public function chekQuestions(Request $request)
{
$request->validate( [
'email' => 'required|string|email',
'answerQuestionOne' => 'required|string|confirmed',
'answerQuestionTwo' => 'required|string'
] );
$user = User::first();
if($user->email == $request->email && $user->answerQuestionOne == $request->answerQuestionOne && $user->answerQuestionTwo == $request->answerQuestionTwo )
{
// $userEmail = DB::table( 'password_resets' )->where( 'token', $user->token );
// return view('auth.password.reset',compact($userEmail));
return view('auth.password.reset');
}
return response()->json( [
'error' => true,
'message' => 'We cannot find a user with that Email Address'
], 404 );
}
Code in reset password.blade
<div id="register" class="animate form registration_form">
<section class="login_content">
<form method="POST" action="{{ url('/main/checklogin') }}" >
#csrf
<h3>د پټ نو بیا راګرځولو لپاره لاندی امنتی پوښتنو ته ځواب ورکړی </h3>
<div class="form-group has-feedback">
<input id="email" type="email" placeholder=" ایمل" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="form-control-feedback">
<i class="fa fa-envelope-o text-muted"></i>
</div>
</div>
<div>
<input id="answerQuestionOne" placeholder="لومړۍ امنیتي پوښتنه" type="text" class="form-control #error('answerQuestionOne') is-invalid #enderror" name="answerQuestionOne" value="{{ old('answerQuestionOne') }}" required autocomplete="answerQuestionOne" autofocus>
#error('answerQuestionOne')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div>
<input id="answerQuestionTwo" placeholder="دوهمه امنیتي پوښتنه " type="text" class="form-control #error('answerQuestionTwo') is-invalid #enderror" name="answerQuestionTwo" value="{{ old('answerQuestionTwo') }}" required autocomplete="answerQuestionTwo" autofocus>
#error('answerQuestionTwo')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<button type="submit" class="btn btn-default btn-block">خوندی کړی </button>
<div class="clearfix"></div>
<div class="separator">
<p class="change_link">
تاسو دمخه غړی یاست ننوتل
</p>
<div class="clearfix"></div>
<br />
</form>
</section>
</div>
You don't need Laravel implementation for this. Just Find a user with the given email and check the answers. After that update the user record with the new password.
In order to fetch user you should do this:
$data = $request->validate( [
'email' => 'required|string|email',
'answerQuestionOne' => 'required|string|confirmed',
'answerQuestionTwo' => 'required|string'
] );
$user = User::where(['email' => $data['email'])->first();
After this just check the answers.
You also need to take the new password from user.

Reset password manually by answering the security questions - Laravel

I want to implement locally forgot password functionality by answering a few security questions where user can reset his/her password without sending reset links via emails.
Here I have tried the below code, in updatePassword.blade.php the email, password, and password-confirm validation is not working so I implement it in the UserControler when I put the email address which is not in the database, or when I put the miss-matched password in the password and password-confirm inputs it throws the below error, but if I put the correct email and password with the matched password in the password and password-confirm inputs it resets my password, I don't know what is wrong.
Any kind of help will be highly appreciated.
ErrorException (E_ERROR) Trying to get property of non-object (View:
C:\xampp\htdocs\Bookstore\resources\views\layouts\layout.blade.php)
(View:
C:\xampp\htdocs\Bookstore\resources\views\layouts\layout.blade.php)
Here are routes in web.php
Route::get('getview', [
'uses' => 'HomeController#getview',
'as' => 'check.getview'
]);
Route::post('chekQuestions', [
'uses' => 'HomeController#chekQuestions',
'as' => 'check.question'
]);
Route::post('updagePassword', [
'uses' => 'HomeController#updagePassword',
'as' => 'update.question'
]);
Here is the code in Controller
public function getview()
{
return view('auth.test');
}
public function chekQuestions(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'answerQuestionOne' => 'required',
'answerQuestionTwo' => 'required'
]);
$user = User::first();
if ($user->email != $request->email) {
return redirect()
->back()
->with(Session::flash('message', 'دا ایمل شتون نلری'))
->withInput();
}
if ($user->answerQuestionOne != $request->answerQuestionOne) {
return redirect()
->back()
->with(Session::flash('message2', 'ځواب مو مطابقت نلری'))
->withInput();
}
if ($user->answerQuestionTwo != $request->answerQuestionTwo) {
return redirect()
->back()
->with(Session::flash('message3', 'ځواب مو مطابقت نلری'))
->withInput();
}
return view('auth.updatePassword',compact('user'));
}
public function updagePassword(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|confirmed|min:8'
]);
$user = User::first();
if ($user->email != $request->email) {
return redirect()
->back()
->with(Session::flash('message', 'دا ایمل شتون نلری'))
->withInput();
} elseif ($request->password_confirmation != $request->password) {
return redirect()
->back()
->with(Session::flash('message2', 'دا ایمل شتون نلری'))
->withInput();
} else {
$user->where('email', $request->email)->update([
'password' => Hash::make($request->password)
]);
return redirect()->route('login');
}
}
Here is the link going to the test view
<a style="font-size: 15px;" href="{{route('check.getview')}}" class="to_register">د پټ نو بیا راګرځول د امنتی پوښتنو له لاری </a>
Here test view
<div class="x_content">
<br>
<form method="POST" action="{{route('check.question')}}" class="form-horizontal form-label-left">
#csrf
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">ایمل
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="email" type="email" placeholder=" ایمل" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#if(Session::has('message'))
<p class="bg-danger">{{session('message')}} </p>
#endif
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">
لومړۍ امنیتي پوښتنه <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="answerQuestionOne" placeholder="لومړۍ امنیتي پوښتنه" type="text" class="form-control #error('answerQuestionOne') is-invalid #enderror" name="answerQuestionOne" value="{{ old('answerQuestionOne') }}" required autocomplete="answerQuestionOne" autofocus>
#if(Session::has('message2'))
<p class="bg-danger">{{session('message2')}} </p>
#endif
#error('answerQuestionOne')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror </div>
</div>
<div class="form-group">
<label for="middle-name" class="control-label col-md-3 col-sm-3 col-xs-12">
دوهمه امنیتي پوښتنه </label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="answerQuestionTwo" placeholder="دوهمه امنیتي پوښتنه " type="text" class="form-control #error('answerQuestionTwo') is-invalid #enderror" name="answerQuestionTwo" value="{{ old('answerQuestionTwo') }}" required autocomplete="answerQuestionTwo" autofocus>
#if(Session::has('message3'))
<p class="bg-danger">{{session('message3')}} </p>
#endif
#error('answerQuestionTwo')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror </div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
{{-- <button type="submit" class="btn btn-primary">انصراف</button> --}}
<button type="submit" class="btn btn-success">خوندی کړی</button>
</div>
</div>
</form>
</div>
Here is the updatePassword.blade.php
<div class="x_content">
<br>
<form method="POST" action="{{route('update.question')}}" class="form-horizontal form-label-left">
#csrf
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">ایمل
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{{-- #foreach ($user as $getemail) --}}
{{-- value="{{ old('email') }}" --}}
<input id="email" type="email" placeholder=" ایمل" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ $user->email }}" required autocomplete="email" autofocus>
{{-- #endforeach --}}
#if(Session::has('message'))
<p class="bg-danger">{{session('message')}} </p>
#endif
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">پټ نوم
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#if(Session::has('message2'))
<p class="bg-danger">{{session('message2')}} </p>
#endif
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">پټ تأیید
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{{-- <input id="passwordconfirm" type="password" class="form-control" name="passwordconfirm" required autocomplete="new-password">
--}}
<input id="password-confirm" type="password" placeholder="دپټنوم تأیید " class="form-control" name="password_confirmation" required autocomplete="new-password">
#if(Session::has('message3'))
<p class="bg-danger">{{session('message3')}} </p>
#endif
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
{{-- <button type="submit" class="btn btn-primary">انصراف</button> --}}
<button type="submit" class="btn btn-success">خوندی کړی</button>
</div>
</div>
</form>
</div>
try this
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|min:6',
'password_confirmation' => 'required|same:password'
]);
I found the solution by manually setting the validation messages
Code in the controller
public function getview(Request $request)
{
$user=new User();
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
return view('auth.question',compact('user','anserone','anstwo'));
}
public function chekQuestions(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'answerQuestionOne' => 'required',
'answerQuestionTwo' => 'required'
]);
$user = User::where('email', $request->email)->first();
if ( $user == null) {
//
$user=new User();
$user->email= $request->email;
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
Session::flash('message', 'دا ایمل شتون نلری');
return view('auth.question',compact('user','anserone','anstwo'));
}
if ( $user->answerQuestionOne == null || $user->answerQuestionTwo == null) {
//
$user=new User();
$user->email= $request->email;
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
Session::flash('message4', 'هیڅ مورد نشته، لمړی تاسی خپل امنیتی ځوابونه خوندی کړی');
return view('auth.question',compact('user','anserone','anstwo'));
}
if ($user->answerQuestionOne != $request->answerQuestionOne) {
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
Session::flash('message2', 'دپښتنو ځوابونه مو ناسم وو');
return view('auth.question',compact('user','anserone','anstwo'));
}
if ( $user->answerQuestionTwo != $request->answerQuestionTwo) {
$anstwo = $request->answerQuestionTwo;
$anserone= $request->answerQuestionOne;
Session::flash('message3', 'دپښتنو ځوابونه مو ناسم وو');
return view('auth.question',compact('user','anstwo','anserone'));
}
return view('auth.updatePassword',compact('user'));
}
public function updagePassword(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|min:8'
]);
// $user = User::first();
$user = User::where('email', $request->email)->first();
if ( $user == null) {
//
$user=new User();
$user->email= $request->email;
// $anserone= $request->answerQuestionOne;
// $anstwo = $request->answerQuestionTwo;
Session::flash('message', 'دا ایمل شتون نلری');
return view('auth.updatePassword',compact('user'));
}
if ($request->password_confirmation != $request->password) {
Session::flash('message3', 'پټ نوم مطابقت نلری');
return view('auth.updatePassword',compact('user'));
}
$user->where('email', $request->email)->update([
'password' => Hash::make($request->password)
]);
return redirect()->route('login');
}

laravel hyn/multi-tenancy override login method using tenant db redirect again login page try to redirect homepage

In hyn/multi-tenancy after overriding the login method in LoginController and within this method connect the tenant database. It login successfully if I print the login results but when I redirect it to homeController it again redirects to the Login Page and doesn't go to the home page. I use
https://github.com/peartreedigital/boilerplate
example only change in loginController which is
class LoginController extends Controller
{
use AuthenticatesUsers;
public function username()
{
$login = request()->input('identity');
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([$field => $login]);
return $field;
}
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function validateLogin(Request $request)
{
$messages = [
'identity.required' => 'Email or username cannot be empty',
'email.exists' => 'Email or username already registered',
'username.exists' => 'Username is already registered',
'password.required' => 'Password cannot be empty',
];
$request->validate([
'identity' => 'required|string',
'password' => 'required|string',
'email' => 'string|exists:users',
'username' => 'string|exists:users',
], $messages);
$domain_name = $request->get('domain_name');
$usernameatacc = $request->get('identity');
$password = $request->get('password');
$hostname = DB::table('hostnames')->select('*')->where('fqdn', $domain_name)->first();
$dbname = DB::table('websites')->select('uuid')->where('id', $hostname->website_id)->first();
Config::set("database.connections.tenant", [
"driver" => 'mysql',
"host" => '127.0.0.1',
"database" => $dbname->uuid,
"username" => 'root',
"password" => ''
]);
Config::set('database.default', 'tenant');
DB::purge('tenant');
DB::reconnect('tenant');
}
public function login(Request $request)
{
$this->validateLogin($request);
$user_data = User::where('email', $request->get('identity'))
->first();
$matchPwd = Hash::check($request->get('password'), $user_data->password);
if ($matchPwd == '1') {
// print_r($user_data);
// Here What can I do????? Please help
}else {
return redirect()->back()->withErrors($user_data);
}
}
protected function guard()
{
return Auth::guard();
}
}
My login form in login.blade.php is
<form method="POST" action="{{ route('login') }}">
#csrf
<div class="form-group row">
<label for="domain_name" class="col-sm-4 col-form-label text-md-right">{{ __('Domain Name') }}</label>
<div class="col-md-6">
<input id="domain_name" type="domain_name" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="domain_name" value="{{ old('domain_name') }}" required autofocus>
#if ($errors->has('domain_name'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('domain_name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="identity" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
#if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
</div>
</div>
</form>
You can redirect user after login with defining either method of redirectTo() or property of $redirectTo.
protected function redirectTo()
{
if (User::check()) {
return route('home');
}
}
or
protected $redirectTo = '/';
Be careful about referring to the name that you've assigned in the route file (default: web.php).

Laravel always sets the default value

I am trying to do registration with user profile picture upload.(I am forced to do it this way)
I created the migration like this:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('nom');
$table->string('prenom');
$table->string('type')->default('visiteur');
$table->boolean('confirme')->default(false);
$table->string('email')->unique();
$table->string('password');
$table->string('photo_url')->default('default_photo_profile.jpg');
$table->rememberToken();
$table->timestamps();
});
the create function :
$request = request();
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
and the form for the file field is like this:
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
everything is working fine except the photo_url field, it always sets the default value in the migration and not the value I set in the create function.
$fullname is initiated and already declared.
the entire form :
<form method="POST" action="{{ route('register') }}" aria-label="{{ __('Register') }}" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<label for="nom" class="col-md-4 col-form-label text-md-right">Nom</label>
<div class="col-md-6">
<input id="nom" type="text" class="form-control{{ $errors->has('nom') ? ' is-invalid' : '' }}" name="nom" value="{{ old('nom') }}" required autofocus>
#if ($errors->has('nom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('nom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="prenom" class="col-md-4 col-form-label text-md-right">Prénom</label>
<div class="col-md-6">
<input id="prenom" type="text" class="form-control{{ $errors->has('prenom') ? ' is-invalid' : '' }}" name="prenom" value="{{ old('prenom') }}" required autofocus>
#if ($errors->has('prenom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('prenom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Mot de pass</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
#if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">Mot de pass confirmation</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
</div>
</div>
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Envoyer
</button>
</div>
</div>
</form>
What is the problem?
Assuming you have a value for $photo_url, make sure you have 'photo_url' in your $fillables.
When you have $fillables, it only inserts (via User::create) what has in that array, otherwise it doesn't submit for that variable.
Your $fillables should look like this:
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
Add 'photo' in $fillable array in User model:
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'photo_url',
];
so according to your code in your model you have to add the photo_url in $fillable array like below.
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
okay now there are 3 ways to do it with $fillable is first way and you are doing it right now.
2nd way:
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
else
{
$fullname = "default_photo_profile.jpg";
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
and in your migration change this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
3rd way:
$fullname = "default_photo_profile.jpg";
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
okay these are the ways to do it. i would prefer first and second way 3rd one is lengthy.
Note: for 2nd and 3rd case you have to change your migration from this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
Hope you get it.

Resources