註冊

2017-05-06 86 views
0

當Laravel PHP註冊,當我創建一個新用戶Laravel ASIGN用戶ID,這樣一來:註冊

User::create([ 
     'name'  => $data['name'], 
     'surname' => $data['surname'], 
     'pass'  => encrypt('password') 
     ]) 

它可以完美的,但現在我想創建一個空的業務,並將其分配給他,像:

Business::create([ 
     'name'  => 'Change the name of your Business', 
     'address' => 'Introduce your address here', 
     'owner_id' => ?? // here would go this new user's ID 
     ]) 

我該如何分配這個新用戶將擁有的ID?他在這一點上還沒有註冊到owner_id = Auth :: user() - > id。那麼我怎麼能做到這一點? 非常感謝!

+1

laravel使用bcrypt()方法來散列密碼。 –

+0

你使用雄辯關係嗎?如果是這樣,你也可以使用'$ business-> owner() - > associate($ user);'。你可以看到設置ID和關聯[這裏]之間的區別(http://stackoverflow.com/questions/31309353/difference-between-setting-id-directly-and-setting-eloquent-associate-relation-w)。 – milo526

回答

1

create方法將返回創建的模型實例,所以你可以將它保存這樣的:

$user = User::create([ 
    'name'  => $data['name'], 
    'surname' => $data['surname'], 
    'pass'  => encrypt('password') 
    ]); 

然後:

Business::create([ 
    'name'  => 'Change the name of your Business', 
    'address' => 'Introduce your address here', 
    'owner_id' => $user->id 
    ]); 
+0

它像一個魅力工作! = D 我不知道用戶是在完成其聲明後創建的。 我記住了..好像我必須做user-> save();在某個時候完成所有的事情。 謝謝! – ButterySAM777