如何获取插入的用户ID并在Laravel的个人资料表中使用它?

时间:2017-01-27 06:00:35

标签: php laravel laravel-5.3

我想为用户添加其他详细信息,我所做的是在注册时创建了一个额外的字段,所以它是这样的:

<h1>Other Details</h1>

    <div class="form-group{{ $errors->has('phone') ? ' has-error' : '' }}">
        <input id="phone" type="text" class="form-control" name="phone"  placeholder="phone number" />
        @if ($errors->has('phone'))
            <span class="help-block">
                <strong>{{ $errors->first('phone') }}</strong>
            </span>
        @endif
    </div>

    <div class="form-group{{ $errors->has('address') ? ' has-error' : '' }}">
        <textarea name="address" id="address" placeholder="your address" class="form-control"></textarea>
        @if ($errors->has('address'))
            <span class="help-block">
                <strong>{{ $errors->first('address') }}</strong>
            </span>
        @endif
    </div>

然后在RegisterController中我在验证中添加了这些字段:

protected function validator(array $data)
    {
        return Validator::make($data, [
            'lastname'  =>  'required|max:255',
            'firstname' =>  'required|max:255',
            'username'  =>  'required|max:16|unique:users',
            'email'     =>  'required|email|max:255|unique:users',
            'password'  =>  'required|min:6|confirmed',

            'phone'     =>  'required',
            'address'   =>  'required'

        ]);
    }

然后在验证部分我没有问题但是在保存到表格中我不知道如何获得插入的用户ID。

我为此配置文件创建了一个迁移:

 public function up()
    {
        Schema::create('user_profile', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->string('phone');
            $table->text('address');
            $table->timestamps();

            $table->foreign('user_id')
                    ->references('id')
                    ->on('users')
                    ->onDelete('cascade');
        });
    }

然后我还为用户档案创建了一个模型

class UserProfile extends Model
{
    protected $table = 'user_profile';

    public function user() {
        return $this->belongsTo('App\User');
    }
}

然后在我的用户模型中我添加了关系:

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'username',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function profile() {
         return $this->hasOne('App\UserProfile');
    }

}

然后我的问题在于保存个人资料。因为在RegisterController中我只有这个:

 protected function create(array $data)
    {
        return User::create([
            'name'      =>  title_case($data['lastname']) . ' ' . title_case($data['firstname']),
            'username'  =>  $data['username'],
            'email'     =>  $data['email'],
            'password'  =>  bcrypt($data['password']),
        ]);
    }

如何添加其他详细信息?我在Laravel还是新手。

4 个答案:

答案 0 :(得分:2)

尝试这样的事情:

$user = new User();        

$user->name = 'John';  

$user->save();

// Now Getting The Last inserted id

$insertedId = $user->id;

echo $insertedId ;

编辑:更改此行:

返回User :: create(...)

$ user = User :: create(...)

并返回

$user or $user->id;

但是检查以确认保存是否成功。

答案 1 :(得分:1)

一个用户有一个user_profile 您可以参考:https://laravel.com/docs/5.3/eloquent-relationships#inserting-and-updating-related-models

尝试这种方法:

$user = new User();
$user->name = 'John Doe';
// rest of the user details
$user->save();

// You can get INSERTED USER_ID
$inserted_user_id = $user->id

// Or you can update user_profile
// without your INSERTED USER_ID very simple
$profile = new Profile();
$profile->address1 = 'Some address';
// rest of address details

$user->profile()->save($profile);
// this is working fine

答案 2 :(得分:1)

 protected function create(array $data)
{

 $user = User::create([
        'name'      =>  title_case($data['lastname']) . ' ' . title_case($data['firstname']),
        'username'  =>  $data['username'],
        'email'     =>  $data['email'],
        'password'  =>  bcrypt($data['password']),
    ]);


 Profile::create([
        'user_id' => $user->id,  
        'phone' => '',
        'address' => '',
    ]);
return $user

}

或者您可以使用$user->userInfo()

$user->userInfo()->save(Profile::create([
        'user_id' => $user->id,  
        'phone' => '',
        'address' => '',
//whatever information you need to save to the userInfo table - if any
]));

Laravel Creating userInfo database table when user registers

答案 3 :(得分:1)

我认为您的代码需要更新如下:

protected function create(array $data)
{
 $userId = DB::table('users')->insertGetId(array(
   'name'      =>  title_case($data['lastname']) . ' ' . title_case($data['firstname']),
   'username'  =>  $data['username'],
   'email'     =>  $data['email'],
   'password'  =>  bcrypt($data['password']),


 ));

 echo $userId;

}

希望这对你有用!