Laravel5.5+ 使用API Resources快速输出自定义JSON方法详解

(编辑:jimmy 日期: 2025/7/5 浏览:2)

从Laravel 5.5+开始,加入了API Resources这个概念。

我们先来看一下官网如何定义这个概念的:

When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users. Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON.

可能看完这个概念之后,你仍然有点不明白,毕竟这个定义说的有点含糊。

如果你熟悉使用API进行输出,构架前后端分离的网络应用,那么你应该会发现,当我们使用Eloquent从数据库中取出数据后,如果想以JSON格式进行输出,那么我们可以使用->toJson()这个方法,这个方法可以直接将我们的model序列化(这个方法从Laravel 5.1+开始就可以使用了):

$user = App\User::find(1);

return $user->toJson();

使用多了,我们会发现,在model较为复杂,或者model中有很多我们API输出可能用不到的字段的情况下,toJson()仍然会忠实地帮我们把这些字段序列化出来。

这个时候,我们会想,如何将model中的某些字段隐藏起来,不输出到JSON中。另外一种情况,比如字段是password等一些敏感信息的时候,我们不希望JSON数据里包含这样的敏感信息。

要解决这个问题,我们可以在model里定义$hidden或者$visible这两个数组来进行字段的隐藏或者显示:

<"htmlcode">
<"htmlcode">
<"htmlcode">
<"htmlcode">
<"htmlcode">
/**
 * Get the customer's full shipping address
 *
 * @return string
 */
public function getFullShippingAddressAttribute()
{
  return "{$this->shippingAddress->country->name} {$this->shippingAddress->province->name} {$this->shippingAddress->city->name} {$this->shippingAddress->address}";
}

但是我们还需要一步操作。由于customers这张表本身没有full_shipping_address这个字段,要使我们的JSON输出包含full_shipping_address,我们需要添加$appends数组:

<"htmlcode">
$ php artisan make:resource Customer

然后我们可以看到,在app/Http文件夹下,多出了一个名为Resources文件夹下,其中含有一个名为Customer.php的文件:

<"htmlcode">
 public function toArray($request)
  {
    return [
      'fullName' => $this->first_name . $this->last_name,
      'fullShippingAddress'  => $this->shippingAddress->country->name . $this->shippingAddress->province->name . $this->shippingAddress->city->name . $this->shippingAddress->address,
    ];
  }

注意到,无论是fullName还是fullShippingAddress,都是不存在于customers表中的字段。

接着,我们只需要简单修改一下我们的控制器:

<"htmlcode">
public function show($id)
{
  $customer = Customer::findOrFail($id);
  return new CustomerResource($customer);
}

要了解更多关于API Resources的详情,请戳官网文档:

https://laravel.com/docs/5.7/eloquent-resources

本文主要讲解了Laravel5.5+ 使用API Resources快速输出自定义JSON方法详解,更多关于Laravel框架的使用技巧请查看下面的相关链接

一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。