📜  如何在 laravel 中使用手机登录 - PHP (1)

📅  最后修改于: 2023-12-03 15:08:41.124000             🧑  作者: Mango

如何在 Laravel 中使用手机登录 - PHP

在现今移动互联网时代,用户越来越多地使用手机浏览网站和应用。因此,在 Web 应用中使用手机登录已经成为一个基本的需求。本文将介绍如何在 Laravel 中使用手机登录。

准备工作

在开始编写代码之前,需要准备以下环境和工具:

  • Laravel 项目
  • 手机号码验证插件 laravel-validation-phone-number
  • 短信发送插件 laravel-sms
  • 数据库
安装插件

安装手机号码验证插件 laravel-validation-phone-number

composer require alhoqbani/validation-phone-number

安装短信发送插件 laravel-sms

composer require aloha/twilio
创建用户表

在 Laravel 中,可以使用 artisan 命令行工具快速创建用户表:

php artisan make:model User -m

create_users_table 迁移文件中添加手机号码和短信验证码字段:

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->string('phone')->unique()->nullable();
    $table->string('verification_code')->nullable();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

在模型类 User.php 中添加手机号码和短信验证码的 fillable 属性:

protected $fillable = [
    'name',
    'email',
    'phone',
    'verification_code',
    'password',
    'remember_token',
];
创建控制器和路由

创建控制器 AuthController.php

php artisan make:controller AuthController

在控制器中添加以下方法:

public function sendVerificationCode(Request $request)
{
    $request->validate([
        'phone' => ['required', 'phone_number'],
    ]);

    $phone = $request->input('phone');

    $verificationCode = mt_rand(100000, 999999);

    try {
        Twilio::message($phone, 'Your verification code is ' . $verificationCode);
    } catch (\Throwable $th) {
        return response()->json(['code' => 500, 'message' => '短信发送失败'], 500);
    }

    User::updateOrCreate(
        ['phone' => $phone],
        ['verification_code' => $verificationCode]
    );

    return response()->json(['code' => 200, 'message' => '短信发送成功'], 200);
}

public function login(Request $request)
{
    $request->validate([
        'phone' => ['required', 'phone_number', 'exists:users'],
        'verification_code' => 'required',
    ]);

    $user = User::where('phone', $request->input('phone'))
        ->where('verification_code', $request->input('verification_code'))
        ->first();

    if ($user) {
        auth()->login($user);
        return response()->json(['code' => 200, 'message' => '登录成功'], 200);
    } else {
        return response()->json(['code' => 401, 'message' => '验证码错误或已失效'], 401);
    }
}

在路由文件 web.php 中添加以下路由:

Route::post('/sendVerificationCode', 'AuthController@sendVerificationCode');
Route::post('/login', 'AuthController@login');
前端页面

在前端页面中,需要创建并发送 POST 请求来获取短信验证码和登录状态。以下是一个简单的示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>手机登录示例</title>
</head>
<body>
    <h1>手机登录示例</h1>
    <form id="login-form">
      <input type="text" name="phone" required><br>
      <button type="button" id="send-verification-code">获取验证码</button><br>
      <input type="text" name="verification_code" required><br>
      <button type="submit">登录</button>
    </form>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(function () {
            $('#send-verification-code').click(function () {
                var phone = $('[name=phone]').val();
                $.post('/sendVerificationCode', {phone: phone}, function (res) {
                    alert(res.message);
                });
            });

            $('#login-form').submit(function (event) {
                event.preventDefault();
                var phone = $('[name=phone]').val();
                var verification_code = $('[name=verification_code]').val();
                $.post('/login', {phone: phone, verification_code: verification_code}, function (res) {
                    alert(res.message);
                }).fail(function (res) {
                    alert(res.responseJSON.message);
                });
            });
        });
    </script>
</body>
</html>
总结

通过以上步骤和代码,我们已经成功地在 Laravel 中实现了手机登录功能。有了这一功能,我们可以吸引更多的移动端用户,并提高用户体验。