以下代码有错误。我使用的是Laravel 5.3和php 7.0。
我谷歌但仍然不清楚,任何帮助将不胜感激。
ActivationService.php
<?php
namespace App;
use Illuminate\Mail\Mailer;
use Illuminate\Mail\Message;
class ActivationService
{
protected $mailer;
protected $activationRepo;
protected $resendAfter = 24;
public function __construct(Mailer $mailer, ActivationRepository $activationRepo)
{
$this->mailer = $mailer;
$this->activationRepo = $activationRepo;
}
public function sendActivationMail($user)
{
if ($user->activated || !$this->shouldSend($user)) {
return;
}
$token = $this->activationRepo->createActivation($user);
$link = route('user.activate', $token);
$message = sprintf('Activate account <a href="%s">%s</a>', $link, $link);
$this->mailer->raw($message, function (Message $m) use ($user) {
$m->to($user->email)->subject('Activation mail');
});
}
public function activateUser($token)
{
$activation = $this->activationRepo->getActivationByToken($token);
if ($activation === null) {
return null;
}
$user = User::find($activation->user_id);
//Below is line 53.
$user->activated = true;
$user->save();
$this->activationRepo->deleteActivation($token);
return $user;
}
private function shouldSend($user)
{
$activation = $this->activationRepo->getActivation($user);
return $activation === null || strtotime($activation->created_at) + 60 * 60 * $this->resendAfter < time();
}
}
错误消息
ActivationService.php第53行中的ErrorException:从空值创建默认对象
上面代码的第53行是这样的:
$user->activated = true;
我怎么能解决这个问题?
答案 0 :(得分:2)
问题很可能是因为$user = User::find($activation->user_id);
返回 null 或 false 。
当你最终遇到这种情况时,总是尝试将变量转储到发生问题的地方,在这种情况下dd($activation->user_id)
我建议改用Auth::user()->id
。