How to send password set(reset link) laravel 7 - laravel

I was trying to send a password reset link to my newly created user and had a hard time trying to find a solution. In case someone has the same issue here is what worked for me in Laravel 7.
Or is there a better way to handle all: add entry in password_resets table and send the notification?
Mail sending properly but i want to send password reset mail to user .Below is the my add controller
public function contactSave(Request $request)
{
$password = Hash::make($request->name);
$validate = $request->validate([
'name' => 'required|regex:/^[\pL\s\-]+$/u',
'email' => 'email',
'phone' => 'digits:10',
'address' => 'required',
'country' => 'required',
'state' => 'required',
// 'comment' => 'required',
'organization' => 'required',
'captcha' => 'required|captcha'
],
[
'captcha.captcha' => 'Incorrect Captcha'
]
);
$user= new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $password;
$user->save();
$CustomerContact= new CustomerContact;
// $CustomerContact->name = $request->name;
// $CustomerContact->email = $request->email;
$CustomerContact->phone = $request->phone;
$CustomerContact->address = $request->address;
$CustomerContact->user_id = $user->id;
$CustomerContact->country_id = $request->country;
$CustomerContact->state_id = $request->state;
$CustomerContact->comment = $request->comment;
$CustomerContact->organization = $request->organization;
$CustomerContact->captcha = $request->captcha;
$CustomerContact->save();
$details = [
'title' => 'Hi '.$request->name.'',
'body' => 'Your account has been created successfully. Request you set your password with this link ???'
];
\Mail::to($request->email)->send(new \App\Mail\ContactMail($details));
return redirect('contacts')->with('success', 'User created successfully.');
}
Anyone here to help me. After saving data in user and employee . I want send email with password reset link to that user id email($request->email).
GIve me simplest solution with kittle explation how to do this

if i correctly understood your problem you can create a route for example: password/reset/user-code
and send it in your email to every user.
you should create a random-code for every user when its created and put it in that link and send in your email.
when user click on that link it will come to your controller and you check that random-code in your database and find your user! and when you have your user you can show them your view for resetting password and save new password
that what i did for password reset before

IF you want to send some data (link or token or everything else) to your mail use this:
Mail::to($request->email)->send(new ContactMail($your_token,$link,$user));
and in your ContactMail class:
class ContactMail extends Mailable
{
use Queueable, SerializesModels;
public $your_token;
public $link;
public $user;
public function __construct($your_token,$link,$user)
{
$this->your_token= $your_token;
$this->link= $link;
$this->user= $user;
}
public function build()
{
return $this->view('email')
->with('your_token',$this->your_token)
->with('link',$this->link)
->with('user',$this->user
}
}

Related

How to create Reset Password token and send email with Mail instead of Notifications?

I have an Email controller in which I'm preparing all email to be sent.
When I send an email, I usually use a method like:
class EmailController extends Controller
{
public function messageReceived(Request $request)
{
$request->validate([
'email' => 'email:rfc,dns',
'body' => 'required',
]);
Mail::to('john.doe#foo.com')->send(
new MessageReceived(
$request->email,
$request->body
)
);
}
}
For the reset password email I'm currently using, I have add the following method to this class:
public function resetPassword(Request $request)
{
$request->validate(['email' => 'required|email|exists:myconnection.users,email']);
$status = Password::broker('users:myconnection')->sendResetLink(
$request->only('email')
);
return $status === Password::RESET_LINK_SENT
? response()->json(['status' => __($status)])
: response()->json(['email' => __($status)]);
}
How to create the token and send the notifiation with Mail::to()->send() instead of sendResetLink() ?
You can manually generate a password reset token through Laravel's Password facade.
// populate user
$user = User::whereEmail($request->email)->first();
// generate token
$token = \Illuminate\Support\Facades\Password::getRepository()->create($user);
You can then pass the token to a custom mailer.
$data = [
'token' => $token,
// ...
];
Mail::to($user)->send(new PasswordResetMailer($data));
In response to your comments:
You can set a custom broker during token generation.
$token = Password::broker('your_custom_broker')->getRepository()->create($user);

Can't login with the correct credentials of a user created from admin panel

I created a UserController where admin can create a user with special privileges, asides from the Laravel Automatic register page, the issue is user creation works fine via the UserController but I can't sign in with the details I used when creating the account. Would appreciate any help I can find on here.
public function create()
{
//
$privileges = privilege::all();
$courses = course::all();
return view('tutor.create')->with('privileges', $privileges)->with('courses',$courses);
}
public function store(Request $request)
{
//
$this->validate($request,[
'name' => 'required',
'email' => 'required',
'password' => 'required',
]);
$users = new User;
$users->name = $request->input('name');
$users->email = $request->input('email');
$users->password = \Hash::make($request['password']);
$users->privilege_id = $request->input('privilege_id');
$users->save();
$course = $request->get('course');
$users->courses()->attach($course);
return redirect('/tutor')->with('success','User created');
}

How to use the reset password mailable given by auth command

I would like to use the reset password mail but in another controller, for I do not know how to code the link in the button for mailtrap or email. So if there is a way of calling the same reset mail password, It would save me some lines. Or if someone could show me how to code that link in another mail function I am okay
Here is the controller I would like to use
public function create()
{
$roles = Role::all();
$addresses = Address::all();
$user = new User();
return view('admin.create', compact('roles', 'addresses', 'user'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'address_id' => 'required',
'name'=> 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'role_id' => 'required',
'description' =>['max:255'],
]);
$quickpass = substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 10 );
$newuser = User::create([
'address_id' =>$request->address_id,
'name'=> $request->name,
'email' => $request->email,
'password' => Hash::make($quickpass),
'role_id' => $request->role_id,
'description'=> $request->description,
]);
Mail::to($newuser->email)
->send(new NewUserPassReset());
return view('admin.index')->with('message','The user has been created and a password reset email has been sent to them.');
}
The NewUserPassReset is the mailable I created on my own which has only the message but does not have the link
Right now, I am using mailtrap and above is my admin controller and he is the one who supposed to create user for me
I will kindly appreciate any help
Check out Illuminate\Auth\Notifications\ResetPassword.php.
It has the url that you're looking for:
url(config('app.url').route('password.reset', ['token' => $token, 'email' => $email]))
As you see, you'll need an email and a token to generate the reset password link.
Assuming you know the email, you can obtain the token with the Illuminate\Support\Facades\Password facade:
$token = \Password::createToken($user)
Hope this helps.

Laravel user update problems

Will try make this clear as much as I can.
Im rolled out a make Auth call in order to use the login and registeration function of laravel and later just used the template to provide the needs I wanted that is.
If user is admin he/she can register a new user.
public function openNewUser(){
return view('auth.register');
}
NB. Part for update.
public function registerNewUser(Request $request){
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::denies('register-user')) {
return redirect()->back();
}
$user->save();
return view('home');
}
Problem 1 - I also want to update user , which is giving problems. The password inputs return empty fields , which i understand. When I try to change it doenst work the confirm password always give a mismatch even though they are the same. When I leave it blank too it doesnt work because the field is required to be filled. I took them off the form and tried if i could edit the email only but only didnt work.
public function userUpdate (Request $request,$user_id) {
$this->validate($request,[
'email' => 'required|email',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::allows('register-user')) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}elseif (Gate::denies('register-user')) {
if (Auth::id() == $user_id) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}else{
return redirect()->back();
}
}
}
Problem 2. I just realized all logins I am doing with my new registration gives These credentials do not match our records.Even though the credentials are there and was registered correctly.
I am using the login provided by laravel but I created my own registration.
Please how can I edit and update my users and also be able to login after registration
What version of Laravel are you using?
Here is my (v5.3) register() method in RegisterController.php, at least part for registration:
public function register(Request $request)
{
...
// save and login user
$user = $this->create($request->all());
$this->guard()->login($user);
...
}
...
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'lastname' => $data['lastname'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
and the login() method from LoginController.php
public function login(Request $request)
{
$credentials = $this->credentials($request);
...
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
}
Hopefully I haven't miss anything.
Keep in mind that things have changed here from version 5.2.
I found out what was wrong , Since I am using Laravel's login my registration had to use bycrypt for the encryption which is what Laravel registration was using , but I was using encrypt when I created my own registration so there was a conflict when logging in. (Remembere I was using Laravels login not my own written Login). I hope this helps someone

laravel 4.2 user roles with auth and Entrust

I look for to make two interface
Administrator (Administrator role)
Subscriber (subscriber role)
I used for now auth and entrust (Github Link) of Laravel 4
A recording User
in my SubscriptionContoller.php I make this :
public function doRegister(){
$password=Input::get('password');
$data = array(
'email' => Input::get('email'),
'password' => Hash::make($password)
);
$rules = array(
'email' => 'required|email',
'password' => 'required'
);
$messages = array(
'required' => 'The :attribute field is required.',
);
$validator = Validator::make($data, $rules, $messages);
if ($validator->fails()) {
Session::flash('message', 'This email is already registered, please choose another one.');
return Redirect::to('subscription/register')
->withErrors($validator);
} else {
$user = new User;
$role = Role::where('name','=','agency')->first();
$user->email = Input::get('email');
$user->password = Hash::make($password);
$user->save();
$user->roles()->attach($role);
Session::flash('message', 'Successfully created account! Please login to submit your ad.');
return Redirect::to('subscription/dashbord');
}
}
How should i write the routes.php and filters.php ??
Just put this line on top of your routes.php
Entrust::routeNeedsRole( 'subscription*', 'agency' );
More Details:
This will only allow users with agency role to be able to access subscription/* urls. If user didn't have that role, then by default an App::abort(403); will be executed, which will look for 403.blade.php in your views/public/ folder.
If you want to do something specific if user didn't match the role, you can pass the third parameter as follow:
Entrust::routeNeedsRole( 'subscription*', 'agency', Redirect::to('/not-authorized'));

Resources