Latest

Thursday, July 6, 2017

laravel not saving custom value to user tabl

Asked by: user3237892


I'm using Laravel 5.4 with a MySql database. I'm trying to extend my user table and save more information when registering a user, but it looks like the value can't be saved to the database.

Here's my migration (only the up method):

Schema::table('users', function (Blueprint $table) {
    $table->string('mobile_phone')->after('remember_token');
});

I've put the mobile_phone element into the $fillable array:

protected $fillable = [
    'name', 'email', 'password', 'mobile_phone'
];

And add the value to the app/Http/Controllers/Auth/RegisterController.php

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'mobile_phone' => 'required|string|unique:users',
        'password' => 'required|string|min:6|confirmed',
    ]);
}

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

Added the input to the form:

<div class="form-group{{ $errors->has('mobile_phone') ? ' has-error' : '' }}">
    <label for="mobile_phone" class="col-md-4 control-label">Mobile</label>
    <div class="col-md-6">
        <input id="mobile_phone" type="text" class="form-control" name="mobile_phone" value="{{ old('mobile_phone') }}" required>

        @if ($errors->has('mobile_phone'))
            <span class="help-block">
                <strong>{{ $errors->first('mobile_phone') }}</strong>
            </span>
        @endif
    <div>
</div>

If I set the value of 'strict' to be true in config/database.php, this error is returned:

SQLSTATE[HY000]: General error: 1364 Field 'mobile_phone' doesn't have a default value (SQL: insert into `users` (`name`, `email`, `password`, `updated_at`, `created_at`) values (Loki, loki@loki.com, $2y$10$9Y1HtCIHLThiwRNklz5WKOT7Y/B0Prpvb9yMJRmlGePhPrLDNFDme, 2017-07-06 19:32:09, 2017-07-06 19:32:09))

When I set that value to false, it saves the new user, but the mobile_phone column is empty.

What am I missing?

Many thanks



Source

No comments:

Post a Comment

Adbox