简体   繁体   中英

Copying an ID when registering an user in Laravel 5.3

I want to copy the content of id into owner_id after someone registers.

$table->increments('id');
$table->integer('owner_id');

How do I do this? I have tried this which I obviously expected not to work:

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        ...
        'owner_id' => $data['id'],


    ]);
}

Since $data only gives you the form information. I am clueless now. Any ideas?

You can do something like:

$user = User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => bcrypt($data['password']);
$user->owner_id = $user->id;
$user->save();

You need to create user first. Only then you can use it's ID:

$user = User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => bcrypt($data['password']),
]);

$user->update(['ownder_id' => $user->id]);

First create the user then update the ownder_id by DB::getPdo()->lastInsertId(); or $user->id .

Try this,

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

    User::where('id', $user->id)
        ->update(['ownder_id' => $user->id]);
    return $user;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM