I am new to Laravel and using Laravel 10. I used Laravel UI for auth setup and it’s working fine but I want to use mobile auth instead of email auth. How can I do it?
<?php
namespace AppHttpControllersAuth;
use AppHttpControllersController;
use AppModelsUser;
use AppNotificationsResetPasswordNotification;
use IlluminateFoundationAuthSendsPasswordResetEmails;
use IlluminateHttpRequest;
use IlluminateSupportFacadesPassword;
class ForgotPasswordController extends Controller
{
use SendsPasswordResetEmails;
protected function credentials(Request $request)
{
return $request->only('mobile');
}
public function sendResetLinkEmail(Request $request)
{
$this->validate($request, ['mobile' => 'required|numeric']);
$user = User::query()->where('mobile', $request->mobile)->first();
var_dump($user);
if (!$user) {
alert('there is not any user');
}
$token = Password::broker()->createToken($user);//this function
$user->notify(new ResetPasswordNotification($token));
return back();
}
}
I get this error
IlluminateAuthPasswordsPasswordBroker::createToken(): Argument #1 ($user) must be of type IlluminateContractsAuthCanResetPassword, null given, called in C:xampphtdocsprojectsyazdvakeraappHttpControllersAuthForgotPasswordController.php on line 48
2
Answers
For changing the authentication method from email to mobile number in Laravel 10, for password reset functionality, you will need to make modification in the code as below,
1.User Model- Add use Notifiable; and change the primary key to mobile:
2.Update the Migration: Update the migration to reflect the changes made to the users table.
3.Update the Validation: update the validation rule in your ‘ForgotPasswordController’ to validate the mobile number instead of the email
4.Update the sendResetLinkEmail Method: update the method to use the mobile number for finding the user and sending the reset password notification
5.Update the notification class: update the ResetPasswordNotification class to use the mobile number instead of the email in the notification message.
6.Update the routes:
7.Update the views releated to password reset to use mobile number instead of email.
–With these above changes the password reset using the mobile number instead of email should work
In Laravel 10 sendResetLinkEmail() function need to defined credentials(), if you’re getting mobile number in request than you need to get email from user object pass manually as credentials() in function, please check the function code :