【问题标题】:How can I get the inserted user id and use it in my profile table in Laravel?如何获取插入的用户 ID 并在 Laravel 的个人资料表中使用它?
【发布时间】:2017-06-12 18:29:12
【问题描述】:

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

<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 的新手。

【问题讨论】:

    标签: php laravel laravel-5.3


    【解决方案1】:

    试试这样的:

    $user = new User();        
    
    $user->name = 'John';  
    
    $user->save();
    
    // Now Getting The Last inserted id
    
    $insertedId = $user->id;
    
    echo $insertedId ;
    

    编辑:更改这一行:

    返回用户::create(...)

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

    然后返回

    $user or $user->id;
    

    但是要检查一下是否保存成功。

    【讨论】:

    • 那么我应该在创建用户数据时删除return并在保存配置文件时移动它吗?
    • 好的,我会尝试这种方法。 :)
    • @Mayank Pandeyz,看来你是 laravel 大师。我需要你的帮助。看这里:stackoverflow.com/questions/41887504/…
    • @mosestoh:不是高手,只是有点知识。
    【解决方案2】:

    一个用户有一个 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
    

    【讨论】:

    • 不客气,但如果它可以解决您的问题,请标记我的答案已完成
    【解决方案3】:
     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-&gt;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

    【讨论】:

      【解决方案4】:

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

      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;
      
      }
      

      希望这对你有用!

      【讨论】:

        猜你喜欢
        • 2020-10-02
        • 1970-01-01
        • 2016-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多