将id参数传递给Laravel中的资源

时间:2018-04-30 13:52:52

标签: php laravel

我的Laravel控制器中有以下方法:

public function specialOffers($id) {
    return \App\Http\Resources\SpecialOfferResource::collection(Offers::all());
}

我需要一些特殊的操作,所以我创建了这个SpecialOfferResource资源。资源代码是:

class SpecialOfferResource extends Resource {
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request) {

        //here I need the $id passed to the controller's method,
        //but I only have $request

        return [
            //my request fields, everything ok
        ];

    }
}

如何将$ id从控制器的方法传递给此资源?我知道我可以作为一个字段传递请求,但这可能是另一种方式吗?

2 个答案:

答案 0 :(得分:1)

资源集合只是一个包装器,用于格式化或映射您传递给它的集合。

您传递的集合是Offers::all(),其中包括所有商品模型。

您可能希望使用查询构建器缩小要传递的集合范围:

public function specialOffers($id) {
    $results = Offers::where('column', $id)->get();
    return \App\Http\Resources\SpecialOfferResource::collection($results);
}

答案 1 :(得分:0)

我不确定这是否可以接受,但在某些情况下我确实需要从控制器传递一些参数来使用toArray资源方法,这就是我所做的。

创建扩展Illuminate\Http\Resources\Json\ResourceCollection

的资源类
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class TestResource extends ResourceCollection
{
   private $id;

   public function __construct($id, $collection)
   {
      parent::__construct($collection);
      $this->id = $id;
   }

   public function toArray($request)
   {
      return [
         'data' => $this->collection,
         'id' => $this->id
      ];
   }
 }

从控制器你可以这样打电话:

<?php

namespace App\Http\Controllers;

use App\Http\Resources\TestResource;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;

class TestController extends Controller
{
   public function index()
   {
      $id = 30;
      $collection = collect([['name' => 'Norli'], ['name' => 'Hazmey']]);

      return new TestResource($id, $collection);
   }
}