Laravel更改集合中的每个模型 [英] Laravel change every model in collection

查看:394
本文介绍了Laravel更改集合中的每个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些物品.现在,在通过api发送之前,我想更改模型的值(但是我不想更新数据库中的模型).

I have a collection of Items. Now, before I am sending it though my api, I want to change a value of the model (but I don't want to update my model in the database).

现在,我想遍历我的集合并将其返回为json,但是我却得到了invalid Payload.

Now I want to loop though my collection and return it as json, but I am getting invalid Payload.

这是我执行的代码:

$trainees = Trainee::select();
        if(!$request->user()->hasPermission('read-trainees')) {
            $trainees->where('status', 1)->where('visible', 1);
        } else {
            $trainees->with(array('user'=>function($query){
                $query->select('id','firstname', 'lastname');
            }));
            $trainees->select('user_id');
        }
        $trainees->select('interested_jobs', 'graduation');
        $trainees = $trainees->get();
        return $trainees
            ->map(function ($item) {
                $item->id = encrypt($item->id);
                return $item;
            })
            ->toJson();

推荐答案

您可以通过多种方式实现这一目标.

You can achieve this in several ways.

每一个雄辩的收藏集扩展了

Every Eloquent collection extends the Collection class, that let you use helpful method like Map():

// get your collection
$trainees = Trainee::all();

// customize them
$trainees->each(function ($trainee) {
  $trainee->id = encrypt($item->id);
});

return $trainees;

PS:默认情况下,当将数组/集合返回给API时,Laravel会将其作为JSON返回.

PS: By default, when returning an array/collection to an API Laravel will return it as JSON.

我认为,第二种方法更为细化,建议使用 API资源.从文档中:

The second approach, more granular and recommended in my opinion, is to use API Resources. From the documentation:

构建API时,您可能需要一个位于 在您的口才模型和实际的JSON响应之间 返回给您应用程序的用户. Laravel的资源类允许 您可以轻松而富有表现力地转换您的模型和模型 收集到JSON中.

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.

因此,您需要:

php artisan make:resource TraineeResource

2.自定义

App \ Http \ Resources \ TraineeResource.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class TraineeResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => encrypt($this->id),
            // ...
        ];
    }
}

3.应用

在您的控制器中:

3. Apply it

In your controller:

App/Http/Controllers/MyCoolController.php

use App\Http\Resources\TraineeResource

public function aCoolMethod(Request $request)
{
    // get your collection
    $trainees = Trainee::all();

    // return it
    return TraineeResource::collection($trainees);
}

这篇关于Laravel更改集合中的每个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆