Laravel - Add Additional Fields To User Profile

[1] Open the Laravel Project

Continue from the previous tutorial https://hashnotes.hashnode.dev/laravel-user-login-and-register-page-with-verify-with-email-feature

[2] Migrate new fields

[2.1] Create migration file

php artisan make:migration add_fields_to_users_table --table=users

[2.2] Edit migration file

(file:app/database/migration/xxxx_xx_xx_xxxx..)

Edit function up() to define two new fields i.e. "mobile" and "gender".

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('mobile')->nullable();
            $table->string('gender')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
};

[2.3] Run migration

Warning: Before running the migration, for windows console developers, you have to edit database path according to the windows path style in the env file e.g. DB_DATABASE=database/rear.sqlite .

Run migration.

php artisan migrate

[3] Update User Model

(file:app/Models/User.php)

Add fields 'mobile' and 'gender' to the $fillable.

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable  implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'mobile',
        'gender'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];
}

[4] Update Request Validation Rule

(file:app/Http/Requests/ProfileUpdateRequest..)

Add the entry 'mobile'=>['string','max:255'] and 'gender'=>['string','max:1'].

<?php

namespace App\Http\Requests;

use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ProfileUpdateRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', Rule::unique(User::class)->ignore($this->user()->id)],
            'mobile'=>['string','max:255'],
            'gender'=>['string','max:1']
        ];
    }
}

Form Requests will have to go through ProfileUpdateRequest before reaching the update method in ProfileController.

[5] Update the Profile Edit form

Add the following codes below the Email field.

    <!-- Mobile -->
    <div>
        <x-input-label for="mobile" :value="__('Mobile')" />
        <x-text-input id="mobile" name="mobile" type="text" class="mt-1 block w-full" :value="old('mobile', $user->mobile)" autocomplete="tel" />
        <x-input-error class="mt-2" :messages="$errors->get('mobile')" />
    </div>

    <!-- Gender -->    
    <div>
        <x-input-label for="gender" :value="__('Gender')" />
        <div class="mt-1">
            <label for="gender_male" class="inline-flex items-center">
                <input id="gender_male" type="radio" name="gender" value="m" class="form-radio" {{ old('gender', $user->gender) === 'm' ? 'checked' : '' }} />
                <span class="ml-2">{{ __('Male') }}</span>
            </label>
            <label for="gender_female" class="inline-flex items-center ml-6">
                <input id="gender_female" type="radio" name="gender" value="f" class="form-radio" {{ old('gender', $user->gender) === 'f' ? 'checked' : '' }} />
                <span class="ml-2">{{ __('Female') }}</span>
            </label>
        </div>
        <x-input-error class="mt-2" :messages="$errors->get('gender')" />
    </div>

[6] Test

Before loading the page, update the database path in env if you ran migration via Windows console (in step 2.3)

Navigate to http://rearnet.test/profile or http://localhost/rearnet/public/profile .

Enter new information for mobile and gender fields.