Search code examples
phplaravellaravel-5.3

How can I get the inserted user id and use it in my profile table in Laravel?


I want to add another details for Users and what I did is I created an extra fields in my registration so it goes like this:

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

Then in RegisterController I added those fields in the validation:

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'

        ]);
    }

Then in the validation part I have no issue but in saving to the table I don't know how can I get the inserted user id.

I created a migration for profile like this:

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

Then I also created a model for the User Profile

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

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

Then in my User model I added the relationship also:

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

}

Then my problem is in the saving of profile. Because in the RegisterController I only have this:

 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']),
        ]);
    }

How can I add my other details? I am still new in Laravel.


Solution

  • One user have one user_profile You can refer to this: https://laravel.com/docs/5.3/eloquent-relationships#inserting-and-updating-related-models

    Try this approach:

    $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