I have a error, I'm using sanctum and I want to check that the email does not exist
the if returns an empty array but the if is satisfied because it returns true
$mail = $request->input(['email']);
if ($search = User::where('email', $mail)->get()) {
return response()->json(['msg' => 'account already exist'], 409);
} else {
$validate = $request->validate([
'name' => 'required|string|',
'email' => 'required|string',
'password' => 'required|string'
]);
}
any solution?
Why not use the Laravel validation since this looks more like validation, so something like:
$request->validate([
'name' => 'required|string|',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string'
]);
with this you don't need to do an if else. You can check the Laravel docs on https://laravel.com/docs/8.x/validation#introduction for more details
Related
i want to edit my user email in laravel, but when i submit the form and then it gives me an error message
The selected Email is invalid.
what do I have to do?
whats wrong with this code?
//in Create Function
'email' => 'required|email|unique:users,email',
//in Update Function is this correct?
'email' => 'required|email|exists:users,email',
Controller
This is my userController for update users
public function update(Request $request, User $user)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string|max:30',
'email' => 'required|email|exists:users,email',
'role' => 'required',
'avatar' => 'required|string|max:150'
],
[],
$this->attributes()
);
if ($validator->fails()) {
$request['role'] = Role::select('id', 'name')->find($request->role);
return redirect()
->back()
->withInput($request->all())
->withErrors($validator);
}
DB::beginTransaction();
try {
$user->update([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'avatar' => parse_url($request->avatar)['path'],
]);
$user->syncRoles($request->role);
Alert::toast(
__('posts.alert.delete.message.success'),
'success'
);
return redirect()->route('users.index');
} catch (\Throwable $th) {
DB::rollBack();
Alert::toast(
__('posts.alert.delete.message.error', ['error' => $th->getMessage()]),
'errors'
);
return redirect()
->back()
->withInput($request->all())
->withErrors($validator);
} finally {
DB::commit();
}
}
You still want a unique validator, so the user can't update their account to someone else's email address and cause a conflict.
However, to prevent it from failing when the user isn't updating their email address (it would fail the unique validation, because a record already exists with that email - the user's own), you'll want to exempt the user's current record from the validation.
https://laravel.com/docs/9.x/validation#rule-unique
See "Forcing A Unique Rule To Ignore A Given ID":
// at the top of your file
use Illuminate\Validation\Rule;
'email' => [
'required',
'email',
Rule::unique('users')->ignore($user->id),
]
You're validating the request requiring the email to exist in the table :
'email' => 'required|email|exists:users,email',
You need to specify unique in order to check the value is not used in the table (same as creation)
'email' => 'required|email|unique:users,email',
You can't do either
'email' => 'exists:users,email'
or
'email' => 'unique:users,email'
for update function. because if you don't change the email you have to submit the old email to the controller which is not "unique" and if you do change it then it doesn't "exist" in the database.
Instead try it like this:
'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($user)],
It means the email should be unique unless it is the email from current user.
See the Laravel docs for more information on this:
https://laravel.com/docs/9.x/validation#rule-unique
This is fresh laravel 9 Project, I didn't touch anything about auth but it is not working.
Route::get('test',function (){
$user = \App\Models\User::create([
'name' => fake()->name(),
'email' => 'a#d.com',
'email_verified_at' => now(),
'password' => bcrypt('password'), // password
]);
dd($user);
});
When i hit /test route, I got new user record.
But when i hit /test2, it returns false
Route::get('test2',function (){
$user = auth()->attempt([
'email' => 'a#d.com',
'password' => 'password'
]);
dd($user);
});
And my config/auth.php is same as default laravel 9 config/auth.php
Any thought?
Laravel encrypts your password by default, so you don't need to encrypt it anymore.
Use this:
$user = \App\Models\User::create([
'name' => fake()->name(),
'email' => 'a#d.com',
'email_verified_at' => now(),
'password' => 'password', // password
]);
I would like to use the reset password mailable for my project but I do not know how to access it in laravel 6.1
Here is my method
public function store(Request $request)
{
$validatedData = $request->validate([
'address_id' => 'required',
'name'=> 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'POBox' =>['required', 'min:6', 'max:6'],
'role_id' => 'required',
]);
$quickpass = substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 10 );
$newuser = User::create([
'address_id' =>$request->address_id,
'name'=> $request->name,
'email' => $request->email,
'POBox'=> $request->POBox,
'password' => Hash::make($quickpass),
'role_id' => $request->role_id,
]);
Mail::to($newuser->email)
->send( );
return view('admin.index')->with('message','The user has been created and a password reset email has been sent to them.');
}
The Notification used is Illuminate\Auth\Notifications\ResetPassword. It builds a MailMessage inline.
The PasswordBroker can be used to create the token and send off the notification for you. The method sendResetLink will take an array of credentials to find the User by.
Illuminate\Auth\Passwords\PasswordBroker
$resp = Illuminate\Support\Facades\Password::broker()->sendResetLink([
'email' => '...',
]);
My route/api.php has these routes:
Route::post('/signup' , 'UserApiController#signup');
Route::post('/logout' , 'UserApiController#logout');
Route::post('/verify' , 'UserApiController#verify');
but when I'm trying to access from Postman like this, it shows object not found:
localhost/my_webiste/api/signup
here the userapicontroller signup function:
public function signup(Request $request)
{
$this->validate($request, [
'social_unique_id' => ['required_if:login_by,facebook,google','unique:users'],
'device_type' => 'required|in:android,ios',
'device_token' => 'required',
'device_id' => 'required',
'login_by' => 'required|in:manual,facebook,google',
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'mobile' => 'required',
'password' => 'required|min:6',
]);
try{
$User = $request->all();
$User['payment_mode'] = 'CASH';
$User['password'] = bcrypt($request->password);
$User = User::create($User);
return $User;
} catch (Exception $e) {
return response()->json(['error' => trans('api.something_went_wrong')], 500);
}
}
here the postman output of post request of localhost/mywebsite/api/signup :
<title>Object not found!</title>
<link rev="made" href="mailto:postmaster#localhost" />
<h1>Object not found!</h1>
The requested URL was not found on this server.
If you entered the URL manually please check your
spelling and try again.
Make sure, in your postman, to add the header accept = application/json.
Your code is correct. It seems like you are missing public from url
localhost/my_webiste/public/api/signup
I need to send an email after a new user is created.
But I don't know how to return to the home page without getting an error.
This is what I am doing right now.
User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'phone' => bcrypt($data['phone']),
'confirmation_code' => str_random(30),
]);
Email_function();
if (Auth::attempt(['email' => $data['email'], 'password' => bcrypt($data['password']) ])) {
// Authentication passed...
return redirect('/');
}
I keep getting this as my error message.
SErrorException in SessionGuard.php line 439:
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /Applications/XAMPP/xamppfiles/htdocs/sniddl/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 63 and defined
Edit:
changed the title to reflect the answer.
Here is a modified create function with an added email function for your register controller
Make sure Request is included in the pages top with namespaces being used:
use Illuminate\Http\Request;
Change the create function in your controller:
protected function create(Request $data)
{
$user = new User;
$user->name = $data->input('name');
$user->username = $data->input('username');
$user->email = $data->input('email');
$user->password = bcrypt($data->input('password'));
$user->phone = bcrypt($data->input('phone'));
$user->confirmation_code = str_random(60);
$user->save();
if ($user->save()) {
$this->sendEmail($user);
return redirect('VIEWPATH.VIEWFILE')->with('status', 'Successfully created user.');
} else {
return redirect('VIEWPATH.VIEWFILE')->with('status', 'User not created.');
}
}
Create the sendEmail function in the same controller that will use Laravels built in email. Make sure you create and your HTML email:
public function sendEmail(User $user)
{
$data = array(
'name' => $user->name,
'code' => $user->confirmation_code,
);
\Mail::queue('EMAILVIEWPATH.HTMLEMAILVIEWFILE', $data, function($message) use ($user) {
$message->subject( 'Subject line Here' );
$message->to($user->email);
});
}
NOTE:
Your going to need to update the VIEWPATH.VIEWFILE and EMAILVIEWPATH.HTMLEMAILVIEWFILE at a minimium in the examples above.
Check the repos below for CONTROLLER :
https://github.com/laravel/laravel/blob/master/app/Http/Controllers/Auth/RegisterController.php
https://github.com/jeremykenedy/laravel-auth/blob/master/app/Http/Controllers/Auth/AuthController.php
REGISTER VIEW(blade) EXAMPLE
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/auth/register.blade.php
EMAIL VIEW THAT RECEIVES VARIABLES:
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/emails/activateAccount.blade.php
Ok so it turns out, by setting User::create as a variable it allows you to login in the user by returning the variable. Like this.
$user = User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'phone' => bcrypt($data['phone']),
'confirmation_code' => str_random(30),
]);
Email_function();
return $user;