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

Laravel 9集成Keycloak时调用User::create()报未定义方法错误

解决Laravel 9 + Keycloak中User::create()未定义的错误

问题原因

你的自定义User模型继承了Vizir\KeycloakWebGuard\Models\KeycloakUser,但这个类仅实现了Laravel的认证接口(Authenticatable),并没有继承Eloquent的Model类,因此失去了create()、save()等Eloquent模型特有的方法,导致填充器调用User::create()时出错。

解决方案

方案1:使用DB门面直接插入数据(快速解决填充问题)

修改UserSeeder,用DB门面直接操作数据库表,绕开模型的限制:

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class UserSeeder extends Seeder
{
    public function run()
    {
        DB::table('users')->insert([
            'firstname' => 'Aaaa',
            'surname' => 'Bbbb',
            'email' => 'ab@first.com',
            'role' => 'superadmin',
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]);
    }
}

方案2:调整User模型继承关系(适配Keycloak+本地Eloquent模型)

如果需要同时保留Eloquent模型功能和Keycloak认证,可以调整模型结构:让User继承Eloquent的Model,并引入Keycloak的认证Trait:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Vizir\KeycloakWebGuard\Traits\KeycloakUserTrait;

class User extends Authenticatable
{
    use HasFactory, Notifiable, KeycloakUserTrait;

    protected $fillable = [
        'firstname',
        'surname',
        'email',
        'role',
    ];

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

调整后需要同步修改config/auth.php的guard配置,确保使用该Eloquent模型作为认证主体,具体可参考包的配置文档调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:35:18