I want to send an SMS to a mobile phone (if he had already turned on the two-factor authentication system).
So at LoginController
I added this method:
protected function authenticated(Request $request, $user) { return $this->loggendin($request , $user); }
And this loggendin
method is inside of a trait called TwoFactorAuthentication
, which goes like this:
trait TwoFactorAuthenticate { public function loggendin(Request $request , $user) { if($user->hasTwoFactorAuthenticatedEnabled()) { auth()->logout(); $request->session()->flash('auth' , [ 'user_id' => $user->id, 'using_sms' => false, 'remember' => $request->has('remember') ]); if($user->two_factor_type == 'sms') { $code = ActiveCode::generateCode($user); // Todo Send Sms $request->user()->notify(new ActiveCodeNotification($code , $user->phone_number)); $request->session()->push('auth.using_sms' , true); } return redirect(route('twofa.token')); } return false; } }
Now the problem is when I want to log in, this message appears on the screen which is saying:
Error Call to a member function notify() on null
Which is referring to this line:
$request->user()->notify(new ActiveCodeNotification($code , $user->phone_number));
And this ActiveCodeNotification
holds some settings for sending the SMS.
If you would like to visit that, here it is:
class ActiveCodeNotification extends Notification { use Queueable; public $code; public $phoneNumber; /** * Create a new notification instance. * * @return void */ public function __construct($code , $phoneNumber) { $this->code = $code; $this->phoneNumber = $phoneNumber; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return [GhasedakChannel::class]; } public function toGhasedakSms($notifiable) { return [ 'text' => "{$this->code}", 'number' => $this->phoneNumber ]; } }
So what’s going wrong here that I get Call to a member function notify() on null while it’s two parameters have value.
So if you know, please let me know. I would really appreciate any idea from you guys…
Thanks.
Advertisement
Answer
Try this:
First, make sure your User model has the Notifiable trait.
Top of the User Model class:
use IlluminateNotificationsNotifiable;
After that:
class User extends Model{ use Notifiable; // ....
And then…
Instead of
$request->user()->notify(new ActiveCodeNotification($code , $user->phone_number));
Use this
$user->notify(new ActiveCodeNotification($code, $user->phone_number));
Or
Before calling auth()->logout();
use it at first:
auth()->user()->notify(new ActiveCodeNotification($code, $user->phone_number));
then, you can call auth()->logout();
Worked for me recently