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

Laravel中User模型添加Eloquent关联报类名重复错误

报错成因

该报错的直接触发原因是同一文件内重复声明了同名类:
你在App\Models命名空间下的User.php文件中,先后定义了两个名为User的类:

  1. 第一个是你自行添加的、继承基础Eloquent模型的class User extends Eloquent,仅包含pekerjaans关联方法
  2. 第二个是Laravel自带的、继承Authenticatable的用户认证类,包含Sanctum、Jetstream相关的认证能力
    PHP不允许同一命名空间下存在两个同名类,因此抛出类名已被占用的错误。
    额外注意:Laravel的用户认证模型必须继承Illuminate\Foundation\Auth\User(即代码中引入的Authenticatable),如果直接继承基础Eloquent模型,会导致登录、权限等认证相关功能完全失效。
修复步骤
  • 删除User.php中你额外添加的、继承Eloquent的重复User类定义,仅保留原有的继承Authenticatable的User类
  • 将pekerjaans()一对多关联方法,直接添加到保留的认证User类内部即可
  • 删除User模型中无用的引用语句use Illuminate\Database\Eloquent\Model as Eloquent;,该类在修正后的User模型中不会被调用
修正后的User.php完整代码
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
     * 一对多关联Pekerjaan模型
     */
    public function pekerjaans(){
        return $this->hasMany(Pekerjaan::class);
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'username',
        'satker',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}
补充说明

你编写的Pekerjaan.php模型代码不存在语法或关联定义错误,其中的user()反向关联方法符合Eloquent一对多关系的定义规范,无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 13:03:21