我有一个 Profile 模型,它与 User 模型具有 OneToOne 关系。如何检查登录用户是否已经拥有配置文件控制器?如果没有创建一个。
谢谢
答案 0 :(得分:0)
试试这个
if (!$user->profile()->exists()) {
Profile::create(['user_id' => $user->id]);
}
或
if (!auth()->user()->profile()->exists()) {
Profile::create(['user_id' => $user->id]);
}
答案 1 :(得分:0)
在laravel中你可以检查关系是否存在
Auth::User()->has('profile')->exists();
或
Auth::user()->profile()->exists();
或
$profile = Auth::User()->profile()->first();
if (!$profile) // when doesn't exists
{
// code goes here
}
答案 2 :(得分:0)
您可以尝试使用 firstOrCreate
来处理它:
$profile = $user->profile()->firstOrCreate([], [
'field' => 'value',
...
]);