Laravel 5表单请求和用户注册

时间:2015-06-25 10:23:54

标签: forms laravel-5

问题是,您需要同时注册用户并使用其数据表格输入另一个表并分配ID

我试过

$data = Request::all();

    $user = new App\User();
    $user->username = $data['name'];
    $user->email = $data['email'];
    $user->password = bcrypt($data['password']);
    $user->save();

如何立即获取新用户ID?

会记录其他数据,例如

$question = new App\Question();
$question->name_q = $data['name_q'];
$question->body_q = $data['body_q'];
$question->user_id = ?

1 个答案:

答案 0 :(得分:0)

您应该为此定义关系,以便您可以轻松插入数据而无需创建两个不同表的对象。让我们先看看你的情况,然后我会告诉你如何更好地做到这一点。

$data = Request::all();

$user = new App\User();
$user->username = $data['name'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->save();

$question = new App\Question();
$question->name_q = $data['name_q'];
$question->body_q = $data['body_q'];
$question->user_id = $user->id;
$question->save();

我们完成了。但是在这种情况下,您必须创建两个不同表的对象并编写现在尚未确定的所有内容,但是当您必须一次性将数据插入到许多表中时会发生什么。让我们看看:

首先定义一个你已经拥有的关系,让我们看看我们应该在模型中拥有什么:

//User model should have a questions function
public function questions()
  {
      return $this->hasMany('App\Question');
  }

//Question model should have a user model
public function user()
 {
        return $this->belongsTo('App\User');
 }

现在我们要做的是

$user = new App\User();
$user->username = $data['name'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->save();


$user->questions()->create([
            'field' => $somevariable,
             'field' => $someothervariable
        ]);
//here questions is the function name in User model