【问题标题】:Check if a user has a profile Laravel 8检查用户是否有个人资料 Laravel 8
【发布时间】:2021-01-07 02:00:51
【问题描述】:

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

谢谢

【问题讨论】:

    标签: laravel laravel-8


    【解决方案1】:

    试试这个

    if (!$user->profile()->exists()) {
       Profile::create(['user_id' => $user->id]);
    }
    

    if (!auth()->user()->profile()->exists()) {
       Profile::create(['user_id' => $user->id]);
    }
    

    【讨论】:

      【解决方案2】:

      在 laravel 中你可以检查关系是否存在

      Auth::User()->has('profile')->exists();
      

      或者

      Auth::user()->profile()->exists();
      

      或者

      $profile = Auth::User()->profile()->first();
      if (!$profile) // when doesn't exists
      {
         // code goes here 
      }
      

      【讨论】:

        【解决方案3】:

        您可以尝试使用firstOrCreate 来处理它:

        $profile = $user->profile()->firstOrCreate([], [
            'field' => 'value',
            ...
        ]);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-11
          • 1970-01-01
          • 1970-01-01
          • 2020-01-23
          • 2015-06-12
          • 1970-01-01
          • 1970-01-01
          • 2012-11-16
          相关资源
          最近更新 更多