检查用户是否有个人资料 Laravel 8

时间:2021-01-06 17:02:21

标签: laravel laravel-8

我有一个 Profile 模型,它与 User 模型具有 OneToOne 关系。如何检查登录用户是否已经拥有配置文件控制器?如果没有创建一个。

谢谢

3 个答案:

答案 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',
    ...
]);