Laravel中如何将HTTP返回的JSON结果转换为自定义Model实例
将接口返回JSON转换为Eloquent模型实例的实现方式
Laravel Eloquent 原生支持脱离数据库手动填充属性生成实例,不需要额外引入第三方包,根据返回数据结构选择对应方法即可:
单条数据场景:使用
forceFill方法忽略字段白名单限制,直接批量赋值属性$response = Http::get('http://example.com'); $data = $response->json(); $example = (new \App\Models\Example())->forceFill($data); // 实例生成后可直接调用模型内定义的方法 $example->statusText();注意:不要使用
fill方法,该方法会受模型$fillable/$guarded字段白/黑名单限制,接口返回的未声明字段会被自动过滤。多条列表数据场景:使用
hydrate方法批量生成模型集合,返回结果和数据库查询返回的集合结构完全一致,可直接调用所有集合方法$response = Http::get('http://example.com/list'); $list = $response->json(); $exampleCollection = \App\Models\Example::hydrate($list); // 批量调用模型方法 $exampleCollection->each->statusText();
如果你的Example模型仅用于处理接口返回数据、不对应实际数据库表,建议在模型内增加两处配置,避免后续误操作触发数据库报错:
class Example extends Model { // 标记模型不存在于数据库,避免save等操作触发更新SQL public bool $exists = false; // 关闭自动维护时间戳,避免接口未返回created_at/updated_at字段时报错 public $timestamps = false; // 原有模型代码... }
更优雅的状态文本实现方案
你当前手动声明$statusText属性、调用方法赋值的写法可以优化为Eloquent访问器实现,不需要额外手动调用方法、不需要单独声明存储属性,访问时自动计算返回:
class Example extends Model { public bool $exists = false; public $timestamps = false; public int $status; /** * 状态文本访问器,直接通过$example->status_text即可获取计算结果 */ public function getStatusTextAttribute(): string { return match($this->status) { 100 => "foo", // 其余状态映射 default => "bar", }; } }
调整后不需要手动调用statusText()方法,填充完属性后直接读取即可:
$example = (new Example())->forceFill($data); // 直接读取,自动触发计算 echo $example->status_text;
如果需要在模型转数组/转JSON返回时自动携带status_text字段,只需在模型内增加$appends配置:
class Example extends Model { // 其余配置... protected $appends = ['status_text']; }
内容的提问来源于stack exchange,提问作者PeterPan
相关产品推荐
相关产品推荐

