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

Laravel 7使用Create创建Eloquent模型后对象为空的问题

Laravel 7 Eloquent创建模型后属性为空/refresh失败问题

问题场景

在Laravel 7中通过Eloquent创建AppUser模型,代码如下:

$appUser = AppUser::create([
    'id' => Str::uuid(),
    'name' => $request->name,                
    'location' => new Point(rand(0,90), rand(0,180))
 ]);

在同一请求中直接访问该对象属性:

$location = $appUser->location;
$name     = $appUser->name; // 虽可从请求获取,但测试用户含大量随机字段,直接访问创建后的属性(含默认值)更便捷

异常情况

偶尔会出现**所有属性为空、id变为0**的情况,仿佛数据库还未完成对象持久化就被访问。尝试在访问前调用refresh(),但$appUser->refresh()有时会抛出错误:

Unknown error: No query results for model [App\Models\AppUser]

这说明对象确实未完成数据库持久化,但PHP线程为何会继续执行后续代码?(运行环境:MariaDB 5.6、PHP 7.4)

相关代码

AppUser模型代码

class AppUser extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * 可批量赋值的属性
     *
     * @var array<int, string>
     */
    protected $fillable = [
      'id',
      'name',
      'location'
    ];

    protected $casts = [
      'id' => 'string'
    ];
}

数据库表结构代码

Schema::create('app_users', function (Blueprint $table) {
    $table->uuid('id')->primary()->unique();
    $table->timestamps();
    $table->boolean('active')->default(true);
    $table->string('name', 128);
    $table->geometry('location')->nullable();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 21:30:01