Powered by Blogger.

LARAVEL:ADDING CUSTOM FIELD BY EDITING THE EXISTING MIGRATION: CREATE_USERS_TABLE.PHP


This is followed in the case where all the data entries stored in the database table to be deleted and once more set up table incorporating new fields.
STEP:1 CREATING A NEW FIELD IN DATABASE
edit the preferred migration from database/migration: create_users_table.php
Find and add $table->integer(‘age’); in Schema
 Schema::create('users', function (Blueprint $table) {
 $table->increments('id');
 $table->string('name');
 $table->integer('age');
 $table->string('email')->unique();
 $table->string('password');
 $table->rememberToken();
 $table->timestamps();
 });
Now after making changes in migration you have to run it using
 $ php artisan migrate:refresh
Now refresh the database users table in PHPMyAdmin to reflect the change.
All the data are flushed and a new field age is also added to the existing field.
STEP:2 ADDING FIELD IN VIEW PAGE
edit register.blade.php from resources/views/auth
nb: put appropriate html tags for div, here purposefully removed to display it
div class="form-group{{ $errors->has('age') ? ' has-error' : '' }}"
 <label for="name" class="col-md-4 control-label">Age</label>

div class="col-md-6"
 <input id="age" type="number" min="1" max="120" class="form-control" name="age" value="{{ old('age') }}" autofocus>

@if ($errors->has('age'))
 <span class="help-block">
 <strong>{{ $errors->first('age') }}</strong>
 </span>
 @endif
 /div
 /div
STEP 3: ADD VALIDATION AND CREATE THE FIELD IN registerController.php from app/Http/controllers/auth
protected function validator(array $data)
 {
 return Validator::make($data, [
 'name' => 'required|string|max:255',
 'age' => 'integer|max:20',
 'email' => 'required|string|email|max:255|unique:users',
 'password' => 'required|string|min:6|confirmed',
 ]);

........
  protected function create(array $data)
 {
 return User::create([
 'name' => $data['name'],
 'age' => $data['age'],
 'email' => $data['email'],
 'password' => bcrypt($data['password']),
 ]);
 }
STEP 4: Update user.php from app/user.php
 protected $fillable = [
 'name','age', 'email', 'password',
 ];
Now try to register and check the database to see the result

No comments