laravel 5.2 - check if field is empty or not - laravel

I want to check if some field is empty or not. If is empty, the user can update the profile without change the current password.
If is not empty, store new value of password. My controller is:
public function storeUpdatedUser(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail(Auth::user()->id);
$user->update($request->all());
$new_password = false;
if($new_password != ""){
$new_password = bcrypt($request->new_password);
$user->password = $new_password;
}
$user->save();
Session::flash('flash_message', 'User updated!');
return redirect('/');
}
but dont work, no password change if I put some value
image explain better

Try this:
public function storeUpdatedUser(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail(Auth::user()->id);
$user->update($request->all());
if(!empty($request->input('new_password'))) {
$new_password = bcrypt($request->input('new_password'));
$user->password = $new_password;
$user->save();
}
Session::flash('flash_message', 'User updated!');
return redirect('/');
}

Laravel Check Request Input Exists
if($request->has('new_password ')) {
dd('new_password is exists.');
} else {
dd('new_password is not exists.');
}
Laravel Check Request Input Field Empty or not
if($request->filled('new_password ')) {
dd('new_password is not empty.');
} else {
dd('new_password is empty.');
}
Laravel Check Request Input Field Empty or not
if(!empty($request->input('new_password '))) {
dd('new_password is not empty.');
} else {
dd('new_password is empty.');
}

This is what works for me in Laravel 5.7:
$user = Auth::user();
$user->update($request->filled('password') ? $request->all() : $request->except(['password']));

Related

not able to authenticate login user in laravel 9

I'm using laravel 9 auth to authenticate the user
my Controller code
login function
public function authLogin(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required|min:5|max:12',
]);
$fnf = User::where('email','=',$request->email)->first();
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
$request->session()->put('LoggedUser', $fnf->uniqueId);
return redirect('dashboard');
}else{
return redirect("/")->with('fail','Please check mail id & password !');
}
}
registration function
public function customRegistration(Request $request)
{
$request->validate([
'firstName' => 'required',
'email' => 'required|email|unique:mania_adminauth',
'number' => 'required|min:10|max:10',
'password' => 'required|min:6',
]);
$data = $request->all();
$arrData['firstName'] = $data['firstName'];
$arrData['lastName'] = $data['lastName'];
$arrData['email'] = $data['email'];
$arrData['number'] = $data['number'];
$arrData['password'] = Hash::make($data['password']);
$arrData['createdOn'] = Carbon::now()->timestamp;
$table = 'mania_adminauth';
$user = new commonModal();
$Response = $user->insertData($table, $arrData);
if ($Response != 0) {
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect("dashboard");
} else {
return view('admin.common.registration')->with('fail','Something Went Wrong !!');
}
}
}
i'm trying to check user is login or not
#if (auth()->check())
<p>User is login.</p>
#else
<p>User is not login.</p>
#endif
but it is showing: "User is not login"
even if i´m logged in
insertData method
public function insertData($table_name, $data)
{
$resp = DB::table($table_name)->insert($data);
return $resp;
}
Please add this line after Auth::attempt(). I think it's the missing points.
$request->session()->regenerate();
It looks like this
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect("dashboard");
}
And it will be run correctly like this

FatalThrowableError in Call to a member function get_one() on null

i have some laravel code like this
public function update_password(Request $request)
{
$data = array(
'password_current' => $request->input('password_current'),
'password_new' => $request->input('password_new'),
'password_new_confirmation' => $request->input('password_new_confirmation'),
);
$rules = [
'password_current' => 'required',
'password_new' => 'required|confirmed',
'password_new_confirmation' => 'required',
];
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
return redirect()->action('Editor\ProfileController#edit_password')->withInput()->withErrors(['New password confirmation failed!']);
} else {
$user = $this->UserRepository->get_one(Auth::user()->id);
if(Hash::check($request->input('password_current'), $user->password))
{
$this->UserRepository->change_password(Auth::user()->id, $request->input('password_new'));
return redirect()->action('Editor\ProfileController#show');
} else {
return redirect()->action('Editor\ProfileController#edit_password')->withInput()->withErrors(['Current password mismatch!']);
}
}
}
but when i run the program, the program notification is FatalThrowableError, Call to a member function get_one() on null. i change with other script in google but no one is work.
$user = $this->UserRepository->get_one(Auth::user()->id);
anyone ever had this problem?
I try to change script like
use Auth;
$user_id = Auth::user()->id;
and still not work.

How to Reset Password without entering email field

I'm creating a reset password with the help of the internet I'm able to make it function, but it needs to input an email address in the email field. I want to hide the email field and only the password field need to input. How can i do that?
My ForgotPasswordController
class ForgotPasswordController extends Controller
{
public function getEmail()
{
return view('auth.passwords.email');
}
public function postEmail(Request $request)
{
$request->validate([
'email' => 'required|email|exists:users',
]);
$token = Str::random(60);
DB::table('password_resets')->insert(
['email' => $request->email, 'token' => $token, 'created_at' => Carbon::now()]
);
Mail::send('auth.verify',['token' => $token], function($message) use ($request) {
$message->from('noreply#taskproph.com');
$message->to($request->email);
$message->subject('Reset Password Notification');
});
Toastr::success('We have e-mailed your password reset link! :)','Success');
return back();
}
}
My ResetPasswordController
class ResetPasswordController extends Controller
{
public function getPassword($token)
{
return view('auth.passwords.reset', ['token' => $token]);
}
public function updatePassword(Request $request)
{
$request->validate([
'email' => 'required|email|exists:users',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
]);
$updatePassword = DB::table('password_resets')->where(['email' => $request->email, 'token' => $request->token])->first();
if(!$updatePassword)
{
Toastr::error('Invalid token! :)','Error');
return back();
}else{
$user = User::where('email', $request->email)->update(['password' => Hash::make($request->password)]);
DB::table('password_resets')->where(['email' => $request->email ])-> delete();
Toastr::success('Your Password has been changed! :)','Success');
return redirect('/login');
}
}
}
In your getPassword method you may get email. Then you can use it email to updatePassword method by passing on it hiddenly.
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Support\Facades\Password;
public function getPassword(Request $request, $token)
{
$email = $request->input('email');
$user = User::where('email', $email)->firstOrFail();
if(!Password::tokenExists($user, $token)) {
Toastr::error('Invalid token!','Error');
return redirect()->route('password.request');
}
return view('auth.passwords.reset', ['token' => $token, 'email' => $email ]);
}
public function updatePassword(ResetPasswordRequest $request)
{
$credentials = $request->validated(); // email, token, password, password_confirmation
$status = Password::reset($credentials, function($user) use($request) {
$user->forceFill([
'password' => bcrypt($request->password)
])->save();
event(new PasswordReset($user));
});
if ($status != Password::PASSWORD_RESET) {
Toastr::error(__($status), 'Error');
return back();
}
$request->session()->flash('statusForgotPassword', __($status));
Toastr::success('Your Password has been changed!','Success');
return redirect('/login');
}
auth.passwords.reset
<input type="hidden" name="email" value="{{ $email }}">

Laravel forgot and reset password API with jwt authentication

please am trying to create a forgot password and reset password API in Laravel using JWT but it gave me this error ' "email": "passwords.throttled"',
I want it to send a password reset link to the email provided but it gives me that error.
or if anyone has any idea of how I will go about it
please can anyone help
this is my code
public function forgotPassword(Request $request){
// $request->validate(['email' => 'required|email']);
$email = $request->only('email');
$rules = ['email'=>'required:users,email'];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
// handler errors
$erros = $validator->errors();
// echo $erros;
return $erros;
}else{
$user = User::where('email', '=', $email)->first();
try {
// verify the credentials and create a token for the user
if (! $token = JWTAuth::fromUser($user)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token'], 500);
}
// if no errors are encountered we can return a JWT
// return response()->json(compact('token'));
$status = Password::sendResetLink($email);
return $status === Password::RESET_LINK_SENT
? response()->json(['status' => $status])
: response()->json(['email' => $status]);
}
}
public function resetPassword(Request $request)
{
// $this->validate($request, [
// 'token' => 'required',
// 'email' => 'required|email',
// 'password' => 'required|confirmed',
// ]);
$rules = ['email'=>'required:users,email','password' => 'required|confirmed',
'token'=>'required '];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
// handler errors
$erros = $validator->errors();
// echo $erros;
return $erros;
}else{
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
// $response = $request->password->reset($credentials, function($user, $password) {
// $user->password = bcrypt($password);
// $user->save();
// $this->auth->login($user);
// });
// return json_encode($response);
}

Manually Passing a Foreign key Value

I can not pass a foreign key value (which is user_id) to my newly created article.
Here is my code...
<?php
if (is_null($request->user_id)) {
$request->user_id = $user->user_id;
}
$request->validate(['title' => 'Required|string|min:3', 'body' => 'Required|string|min:5', 'user_id' => 'Required|exists:users,user_id']);
if ($article = Article::create($request->all())) {
event(new ArticleCreated($user));
return response()->json(['success' => true, 'reason' => 'Article Created successfully', $article]);
} else {
return 'Article could not be created';
}
Change this:
if($article = Article::create($request->all())) {
$article->user_id = $request->user_id;
$article->save();
event(new ArticleCreated($user));
return response()->json(['success' => true, 'reason' => 'Article Created successfully', $article]);
}
Try this,
public function store(Request $request)
{
$request->validate([
'title' => 'Required|string|min:3',
'body' => 'Required|string|min:5',
]);
$data = $request->all();
//you don't need to validate user_id is correct
//if you are using auth middleware in the route
$user = auth()->user()
$data['user_id] = $user->id
if ($article = Article::create($data)) {
event(new ArticleCreated($user));
return response()->json([
'success' => true,
'reason' => 'Article Created successfully',
$article
]);
} else {
return 'Article could not be created';
}
}
Hope this helps
Check your fillable array in Article model, there must be user_id, and check if the user id is passed in the $request->all().

Resources