无为清净楼资源网 Design By www.qnjia.com

从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框架的使用技巧请查看下面的相关链接

标签:
Laravel5.5,API,Resources使用方法,Laravel5.5输出自定义JSON方法,Laravel5.5输出自定义JSON

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com