You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel手动调用auth()->user()返回User模型keyType为int如何修复

问题原因

问题核心来自两点:

  1. auth()->user($user)不是Laravel官方支持的写法,auth()->user()本身无参数,作用仅为获取当前登录用户,传参的行为既不会生效,也不会触发自定义模型的初始化流程。
  2. 你编写的Uuidable trait配置覆盖不全,keyType仅在初始化方法中设置,incrementing仅在创建事件中临时修改,二者都没有覆盖模型的全局默认配置。

修复步骤

1. 修正手动设置登录用户的写法

如果需要手动将指定用户设为当前登录用户,使用官方提供的方法:

  • 持久化登录(写入session):auth()->login($user)
  • 仅当前请求生效:auth()->setUser($user)

2. 补全Uuidable trait的配置

直接在trait中声明属性覆盖父类默认值,优先级高于父类配置,不需要依赖事件或初始化方法触发:

<?php

namespace App\Traits;

use Ramsey\Uuid\Uuid;

trait Uuidable
{
    // 直接覆盖父类默认配置,所有场景实例化都生效
    public $incrementing = false;
    protected $keyType = 'string';

    /**
     * 兼容旧版本Laravel的实例化场景
     */
    public function initializeUuidable()
    {
        $this->setKeyType('string');
    }

    /**
     * 为模型设置主键
     *
     * @return void
     */
    public static function bootUuidable()
    {
        static::creating(function ($model) {
            if (!isset($model->attributes[$model->getKeyName()])) {
                $uuid = Uuid::uuid4();
                $model->attributes[$model->getKeyName()] = $uuid->toString();
            }
        }, 0);
    }
}

3. 确认Auth配置正确

检查config/auth.php中用户提供者的配置,是否指向你引入了Uuidable trait的自定义User模型:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class, // 不要使用基础类Illuminate\Foundation\Auth\User
    ],
],

4. 确认自定义User模型引入了Uuidable trait

检查App\Models\User类是否正确引入了trait:

namespace App\Models;

use App\Traits\Uuidable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Uuidable; // 确认引入该trait

    // 其余模型配置
}

修改完成后执行php artisan config:clear清除配置缓存,再测试即可生效。

内容的提问来源于stack exchange,提问作者Liam Seys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:54:03