Laravel 8出现Call to undefined method stdClass::notify()错误求助
问题原因与修复方案
核心报错根源
你遇到的Call to undefined method stdClass::notify()错误,本质是通过DB::table('users')查询返回的是PHP原生stdClass对象,不是你定义的User模型实例。只有引入了Notifiable trait的User模型实例才自带notify()方法,普通stdClass对象没有这个方法,即使用Notification::send也要求传入Notifiable实例,所以两种写法都报错。
具体修复步骤
1. 修正控制器代码,替换DB门面操作为User模型操作
控制器里不需要引入Notifiable trait(通知是发给用户的,不是发给控制器的),删除冗余的trait引入,所有用户查询更新逻辑都用User模型处理:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Admin; use App\Models\User; use RealRashid\SweetAlert\Facades\Alert; use App\Notifications\AccountVerificationEmail; use Illuminate\Support\Facades\Notification; class UserController extends Controller { public function update_verify($id){ // 直接用模型查询,得到User实例,不是stdClass $user = User::findOrFail($id); // 切换submitted状态 $user->submitted = $user->submitted == 0 ? 1 : 0; $user->save(); // 此时$user是带Notifiable的模型实例,可以直接调用notify // 注意你原来的通知类构造函数需要传参,这里要把$user传进去 $user->notify(new AccountVerificationEmail($user)); return redirect('verify')->with('success','User has been verified!'); } }
2. 清理User模型冗余代码
你的User模型重复引入了多次Notifiable trait,删除冗余部分即可,最终模型代码:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; class User extends Model { use HasFactory, Notifiable; }
3. 通知类可选调整
如果你的通知类里不需要用到传入的$vermail变量,可以直接删除构造函数和对应的私有属性,调用的时候就不需要传参了,避免传参遗漏报错。
内容的提问来源于stack exchange,提问作者Tracy
相关产品推荐
相关产品推荐

