1

我正在使用以下特征为我的用户模型生成 UUID。我已经为以下事件设置了一个侦听器:Illuminate\Auth\Events\Login。这在你正常登录应用程序(使用 Laravel Breeze)时有效。但是当我手动执行 auth()->user($user) 时,我会返回一个 Illuminate\Foundation\Auth\User 的实例,其中 keyType 是一个整数并且递增设置为 true,尽管我的 trait 不是这样。

任何人都知道如何解决这个问题?

<?php

namespace App\Traits;

use Ramsey\Uuid\Uuid;

trait Uuidable
{
    /**
     * Cast the primary key type as a string
     */
    public function initializeUuidable()
    {
        $this->setKeyType('string');
    }

    /**
     * Set the model to none incrementing
     *
     * @return bool
     */
    public function getIncrementing()
    {
        return false;
    }

    /**
     * Set the key of the model
     *
     * @return void
     */
    public static function bootUuidable()
    {
        static::creating(function ($model) {
            if (!isset($model->attributes[$model->getKeyName()])) {
                $model->incrementing = false;
                $uuid = Uuid::uuid4();
                $model->attributes[$model->getKeyName()] = $uuid->toString();
            }
        }, 0);
    }
}

Illuminate\Foundation\Auth\User {#1494 ▼
  #connection: "mysql"
  #table: "users"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:13 [▶
    "id" => "31f12e1a-964c-4580-8a20-263c8bb7bf95"
    "first_name" => "test"
    "last_name" => "user"
    "email" => "test@mrpackage.com"
    "email_verified_at" => null
    "password" => "$2y$10$vTAYxvC4s95PpF5BmzC0p..ZiQfcn3WARxXalgmd1kVZn5X1S/F02"
    "last_login_id" => null
    "remember_token" => null
    "welcome_valid_until" => null
    "printer_id" => null
    "created_at" => "2021-09-15 14:38:00"
    "updated_at" => "2021-09-15 14:38:20"
    "deleted_at" => null
  ]
  #original: array:13 [▶
    "id" => "31f12e1a-964c-4580-8a20-263c8bb7bf95"
    "first_name" => "test"
    "last_name" => "user"
    "email" => "test@mrpackage.com"
    "email_verified_at" => null
    "password" => "$2y$10$vTAYxvC4s95PpF5BmzC0p..ZiQfcn3WARxXalgmd1kVZn5X1S/F02"
    "last_login_id" => null
    "remember_token" => null
    "welcome_valid_until" => null
    "printer_id" => null
    "created_at" => "2021-09-15 14:38:00"
    "updated_at" => "2021-09-15 14:38:20"
    "deleted_at" => null
  ]
  #changes: array:3 [▶
    "password" => "$2y$10$vTAYxvC4s95PpF5BmzC0p..ZiQfcn3WARxXalgmd1kVZn5X1S/F02"
    "welcome_valid_until" => null
    "updated_at" => "2021-09-15 14:38:20"
  ]
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▶
    0 => "*"
  ]
  #rememberTokenName: "remember_token"
}
4

0 回答 0