Laravel 8 - 用户认证添加手机号

本文旨在使用 Laravel 8 的 Jetstream 认证功能添加简单的手机号选项。

一、添加 Jetstream 和 Livewire

此处参考 learnku 的 Laravel 8 中文文档,安装 Jetstream 和 Livewire:

composer require laravel/jetstream
php artisan jetstream:install livewire

二、修改用户模型

在用户模型中,需要添加 phone 字段,即需要在 Model 和 Migration 中进行修改,并添加手机号验证规则(Rule)

1、修改 Model

修改 app/Models/User.php

class User extends Authenticatable
{
    protected $fillable = [
        'name',
        'phone',
        'email',
        'password',
    ];
}

2、修改 Migration

修改 database/migrations/2014_10_12_000000_create_users_table.php

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('phone')->unique();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->foreignId('current_team_id')->nullable();
            $table->text('profile_photo_path')->nullable();
            $table->timestamps();
        });
    }
}

3、添加验证规则

使用 artisan 添加一个新规则:

php artisan make:rule phone

此时在 app/Rules 目录下会生成 phone.php,在文件的 passes 方法中添加手机号的格式检查和错误提示信息:

class phone implements Rule
{
    public function passes($attribute, $value)
    {
        //
        if (strlen($value) == 11 && is_numeric($value)){
            $heads = ['13', '15', '17', '18'];
            foreach ($heads as $head){
                if (stripos($value, $head) == 0) return true;
            }
        }
        return false;
    }

    public function message()
    {
        return 'The Phone Number is not correct.';
    }
}

在这里仅简单检查了数字个数及前两位数。

三、修改注册界面和 Profile 界面

修改界面需要在 resources 中对 view 模板添加 phone 字段。

1、修改注册界面

修改 resources/views/auth/register.blade.php

<form method="POST" action="{{ route('register') }}">
    @csrf
    <div>
        <x-jet-label for="name" value="{{ __('Name') }}" />
        <x-jet-input id="name" class="block mt-1 w-full" type="text" name="name" :value="old('name')" required autofocus autocomplete="name" />
    </div>

    <div class="mt-4">
        <x-jet-label for="phone" value="{{ __('Phone') }}" />
        <x-jet-input id="phone" class="block mt-1 w-full" type="text" name="phone" :value="old('phone')" required />
    </div>

    <div class="mt-4">
        <x-jet-label for="email" value="{{ __('Email') }}" />
        <x-jet-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required />
    </div>

    <div class="mt-4">
        <x-jet-label for="password" value="{{ __('Password') }}" />
        <x-jet-input id="password" class="block mt-1 w-full" type="password" name="password" required autocomplete="new-password" />
    </div>

    <div class="mt-4">
    	<x-jet-label for="password_confirmation" value="{{ __('Confirm Password') }}" />
        <x-jet-input id="password_confirmation" class="block mt-1 w-full" type="password" name="password_confirmation" required autocomplete="new-password" />
    </div>

    <div class="flex items-center justify-end mt-4">
        <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('login') }}">
        	{{ __('Already registered?') }}
        </a>

        <x-jet-button class="ml-4">
            {{ __('Register') }}
        </x-jet-button>
    </div>
</form>

这个改动是在 form 块中添加了一个 phone 的输入框。

2、修改 Profile 界面

resources/views/profile/update-profile-information-form.blade.php 中找到以下字段,添加 phone 的输入框:

<x-slot>
    <!-- Name -->
    <div class="col-span-6 sm:col-span-4">
        <x-jet-label for="name" value="{{ __('Name') }}" />
        <x-jet-input id="name" type="text" class="mt-1 block w-full" wire:model.defer="state.name" autocomplete="name" />
        <x-jet-input-error for="name" class="mt-2" />
    </div>

    <!-- Email -->
    <div class="col-span-6 sm:col-span-4">
        <x-jet-label for="email" value="{{ __('Email') }}" />
        <x-jet-input id="email" type="email" class="mt-1 block w-full" wire:model.defer="state.email" />
        <x-jet-input-error for="email" class="mt-2" />
    </div>

    <!-- Phone -->
    <div class="col-span-6 sm:col-span-4">
        <x-jet-label for="phone" value="{{ __('Phone') }}" />
        <x-jet-input id="phone" type="text" class="mt-1 block w-full" wire:model.defer="state.phone" />
        <x-jet-input-error for="phone" class="mt-2" />
    </div>
</x-slot>

这个改动是在 x-slot 块中添加了一个 phone 的输入框。

四、修改注册和 Profile 行为

在注册和用户 Profile 界面进行用户信息创建和修改的时候,还需要对控制器进行修改来添加对手机号的支持。控制器目录为 app/Actions/Fortify

1、修改注册行为

注册行为的控制器为 app/Actions/Fortify/CreateNewUser.php ,需要修改 create 方法:

class CreateNewUser implements CreatesNewUsers
{
    public function create(array $input)
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'phone' => ['required', 'string', new phone],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => $this->passwordRules(),
        ])->validate();

        return User::create([
            'name' => $input['name'],
            'phone' => $input['phone'],
            'email' => $input['email'],
            'password' => Hash::make($input['password']),
        ]);
    }
}

此处主要是添加了验证规则和模型参数。

2、修改 Profile 更新行为

注册行为的控制器为 app/Actions/Fortify/UpdateUserProfileInformation.php ,需要修改 updateupdateVerifiedUser 方法:

class UpdateUserProfileInformation implements UpdatesUserProfileInformation
{
    public function update($user, array $input)
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'phone' => ['required', new phone],
            'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
            'photo' => ['nullable', 'image', 'max:1024'],
        ])->validateWithBag('updateProfileInformation');

        if (isset($input['photo'])) {
            $user->updateProfilePhoto($input['photo']);
        }

        if ($input['email'] !== $user->email &&
            $user instanceof MustVerifyEmail) {
            $this->updateVerifiedUser($user, $input);
        } else {
            $user->forceFill([
                'name' => $input['name'],
                'email' => $input['email'],
                'phone' => $input['phone'],
            ])->save();
        }
    }

    protected function updateVerifiedUser($user, array $input)
    {
        $user->forceFill([
            'name' => $input['name'],
            'phone' => $input['phone'],
            'email' => $input['email'],
            'email_verified_at' => null,
        ])->save();

        $user->sendEmailVerificationNotification();
    }
}

注意两个方法中 phone 字段的修改。


到此,已经成功添加了手机号的字段。按此方法还可以添加其他的自定义字段。虽然没有发送验证码之类的验证功能,但是也算是提供了一个基础功能。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值