首页 > 解决方案 > 做一个返回多个创建函数 Laravel

问题描述

刚做完一个php artisan make:authapp\Http\Controllers\Auth\RegisterController就在默认的create函数里:

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}

我在此默认视图 ( /register) 的同一页面的视图中添加了另一个模型的出生日期。如何在相同的默认创建函数中插入新的创建函数?

在此处输入图像描述

UserInformation::create([
    'user_id' => ???
    'birth_date' => $data['birth_dae']
]);

如何将其连接到上述return语句,以及如何从 the 中获取新创建idUser并将其传递给user_idof UserInformation

到目前为止我的想法:

protected function create(array $data)
{
    return [
        User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        ]),
        UserInformation::create([
        'user_id' => ??? // should be the same as the id of the created user
        'birth_date' => $data['birth_date'],
        'color' => "blue"
        ])
    ];
}

尝试做这样的事情:

protected function create(array $data)
{
    $user = new User;
    $user->name = $data['name'];
    $user->email = $data['email'];
    $user->password = Hash::make($data['password']);
    $user->save();

    $user_id = $user->id;

    $user_info = new UserInformation;
    $user_info->user_id = $user_id;
    $user_info->birth_date = $data['birth_date'];
    $user_info->color = "blue";
    $user_info->save();

    return view('home');
}

但仍然返回此错误:

传递给 Illuminate\Auth\SessionGuard::login() 的参数 1 必须实现接口 Illuminate\Contracts\Auth\Authenticatable,给出 Illuminate\View\View 的实例

编辑:

我的一个好朋友推荐了这个:

protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'pasword' => Hash::make($data["password"])
    ]);

    UserInformation::create([
        'user_id' => $user->id,
        'birth_date' => $data['birth_date'],
        'color' => 'blue'
    ]);

    return $user;
}

在我的 UserInformation 模型中:

protected $fillable = ["user_id", "birth_date", "color"];

标签: laravel-5

解决方案


如果我没记错的话,会根据函数的结果return Model::create(...);简单地返回true或(或死于错误) ,所以我们可以调整代码来处理这个问题。尝试以下操作:falsecreate()

protected function create(array $data){
  \DB::beginTransaction();

  try {
    $user = User::create([
      "name" => $data["name"],
      "email" => $data["email"],
      "password" => Hash::make($data["password"])
    ]);

    $userInformation = UserInformation::create([
      "user_id" => $user->id,
      "birth_date" => $data["birth_date"],
      "color" => "blue"
    ]);
  } catch(\Exception $ex){
    \DB::rollBack();
    \Log::error("Error creating User and UserInformation: ".$ex->getMessage());

    return false;
  }

  \DB::commit();

  return true;
}

通过设置$user为 的结果User::create(),可以$user->id在后续使用UserInformation::create()。另外,我建议在保存依赖记录时使用事务。如果User::create()成功和UserInformation::create()失败,你不会得到一个User没有 no的结果UserInformation,因为整个事务在失败时回滚,并在成功时持久化到数据库中。


推荐阅读