Sending custom verification emails from a controller method - laravel

I have some data i am receiving from new users and extracting the email to send to the new user. This is how i am doing it
public function register_mechanic_post(Request $request)
{
$validatedData = $request->validate([
'email' => 'required|email|unique:users',
'password' => 'required',
'password_confirmation' => 'required'
], [
'email.required' => 'Email address is required',
'password.required' => 'Password field is required',
'password_confirmation.required' => 'Password confirmation field is required'
]);
$data = $request->all();
$name = $request->input('name');
$data['role'] = 'manager';
$email = $request->input('email');
User::create([
'email' => $request->input('email'),
'name' => $request->input('name'),
'role' => 'manager',
'password' => Hash::make($request->input('password')),
//'email_verified_at' => now()
]);
$user = User::where('email','=',$email)->first();
$user->sendEmailVerificationNotification();
return back()->with('success', 'Mechanic created successfully.');
}
I am getting this error
403 THIS ACTION IS UNAUTHORIZED
The docs say its because of signed urls https://laravel.com/docs/9.x/urls#signed-urls
I haven't modified the existing email verification code as shipped with laravel. How do i use the signed urls feature in my case?.

Not an answer, but your code could be significantly simpler, making it easier to manage in the future.
public function register_mechanic_post(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
'password_confirmation' => 'required'
], [
'email.required' => 'Email address is required',
'password.required' => 'Password field is required',
'password_confirmation.required' => 'Password confirmation field is required'
]);
$user = User::create([
'email' => $validatedData['email'],
'name' => $validatedData['name'],
'role' => 'manager',
'password' => Hash::make($validatedData['password']),
'email_verified_at' => now()
]);
$user->sendEmailVerificationNotification();
return back()->with('success', 'Mechanic created successfully.');
}
But why ask the user to verify their email when you are already setting the email_verified_at timestamp (indicating that verification has been performed)

Related

Laravel 8: How to send validation response in JSON format using postman

I have this validation, how can I return an error response in postman?
please help guys.
$rules = [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
];
$validator = $this->validate($request, $rules);
$data = $request->all();
use Illuminate\Support\Facades\Validator;
Then write validation like
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
]);
if ($validator->fails()) {
return response()->json([
'message' => 'Invalid params passed', // the ,message you want to show
'errors' => $validator->errors()
], 422);
}

User create and update using updateOrCreate()

I am creating and updating user using below code.
public function store(Request $request)
{
if ($request->ajax()) {
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users,email,' .$request->user_id,
'password' => 'required',
'role' => 'required',
]);
$user = User::updateOrCreate(['id' => $request->user_id],
[
'name' => $request->name,
'email' => $request->email,
'role' => $request->role,
'password' => Hash::make($request->password)
]);
}
}
When I am updating record Password is updating also. How can I solve the issue ?
How validation is working here 'email' => 'required|email|unique:users,email,' .$request->user_id, when I am creating a record ? Because when I am creating a record at that time $request->user_id is not available.

parse_url() expects parameter 1 to be string, array given when creating user laravel

Im building my onw registration in laravel and when im trying to hash my password i get the error parse_url() expects parameter 1 to be string, array given
//Controller
HomeController.php
$filteredValidation = $request->except('_token');
$password = Hash::make($filteredValidation['password']);
UserRegistrationRequest::create([
'firstname' => $filteredValidation['firstname'],
'lastname' => $filteredValidation['lastname'],
'email' => $filteredValidation['email'],
'year' => $filteredValidation['year'],
'avatar' => $filteredValidation['firstname'],
'buddy' => $filteredValidation['firstname'],
'password' => $password,
]);
//request
UserRegistrationRequest.php
public function rules()
{
return [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'year' => 'required',
'password' => 'required',
];
}
I have no idea why this is happening

How can i pass only one message for all fields

This is code of register function which generate error of success and failure.
public function register(Request $request) {
$validator = Validator::make($request->all(),
[
'user_type' => 'required',
'fname' => 'required',
'lname' => 'required',
'dob' => 'required',
'phone' => 'required',
'gender' => 'required',
'uname' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['failed'=>$validator->errors()], 401); }
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('AppName')->accessToken;
$success['status'] = true;
$success['data'] = [$user];
$success['message'] ="User created successfully!";
// return response()->json([
// "message" => " record created"
// ], 201);
return response()->json($success, $this->successStatus);
}
This is my output
1.All error message show in one line..This is my main point..But i want to actually this message of This image...How can i do that?
2.Second thing in API if any user put same email id api give json error not laravel error..
Try this:
return response()->json(['status'=> False, 'msg' => 'This is not successful'], 401);
You can pass custom json in response instead of validator response.
For checking if email exists update the validation like this:
'email' => 'required|email|unique:users,email',
where users is your table name and email is your column name
You just need to replace your code
if ($validator->fails()) {
return response()->json(['failed'=>$validator->errors()], 401);
with
if ($validator->fails()) {
return response()->json(['status'=> 'False', 'msg' => 'This is not sccessfully'], 401);

How to access the reset password mailable in the new version of laravel

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' => '...',
]);

Resources