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

Laravel 8:解决执行migrate:fresh --seed时读取null的id属性错误

解决php artisan migrate:fresh --seed执行时的Auth用户错误

问题原因

执行迁移或种子文件时,系统处于命令行环境,没有HTTP请求上下文,Auth::user()会返回null。此时直接访问$user->id会抛出「试图获取非对象的属性'id'」的错误。另外你的代码里还有个语法错误:model->created_by缺少变量前缀$,应该是$model->created_by。

修复方案

方案1:安全处理null用户(推荐)

使用PHP的空安全运算符?->和空合并运算符??,避免null属性访问:

parent::boot();

static::creating(function($model)
{
    $user = Auth::user();
    $model->created_by = $user?->id ?? 1;
});

static::updating(function($model)
{
    $user = Auth::user();
    $model->updated_by = $user?->id ?? 1;
});
  • $user?->id:如果$user是null,直接返回null,不会触发报错
  • ?? 1:如果前面的结果是null,就使用默认值1

方案2:区分命令行与Web环境

如果迁移/seed时需要单独处理用户字段,可以判断当前运行环境:

parent::boot();

static::creating(function($model)
{
    // 仅在Web请求中获取登录用户,命令行环境直接用默认值
    if (!app()->runningInConsole()) {
        $user = Auth::user();
        $model->created_by = $user?->id ?? 1;
    } else {
        $model->created_by = 1;
    }
});

static::updating(function($model)
{
    if (!app()->runningInConsole()) {
        $user = Auth::user();
        $model->updated_by = $user?->id ?? 1;
    } else {
        $model->updated_by = 1;
    }
});

内容的提问来源于stack exchange,提问作者Babur Shah Sayer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:01:08