Php 将id参数传递给Laravel中的资源
我的Laravel控制器中有以下方法:Php 将id参数传递给Laravel中的资源,php,laravel,Php,Laravel,我的Laravel控制器中有以下方法: public function specialOffers($id) { return \App\Http\Resources\SpecialOfferResource::collection(Offers::all()); } 我需要一些特殊的操作,所以我创建了这个SpecialOfferResource资源。资源代码为: class SpecialOfferResource extends Resource { /** *
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从控制器的方法传递到此资源?我知道我可以将请求作为一个字段传递,但是否有可能以其他方式传递?资源集合只是一个包装器,用于格式化或映射传递给它的集合 您传递的集合是
Offers::all()
,它将包括所有的Offers模型
您可能希望使用查询生成器缩小要传递的集合的范围:
public function specialOffers($id) {
$results = Offers::where('column', $id)->get();
return \App\Http\Resources\SpecialOfferResource::collection($results);
}
我不确定这是否可以接受,但在某些情况下,我确实需要从控制器传递一些参数以在toArray资源方法中使用,这就是我所做的 创建扩展
illighted\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
];
}
}
如果传递ID,则不会使用集合。您将使用资源的单个实例。相同的$ID对集合中的所有项目都很有用。$ID不是报价模型的一列。我需要$id来进行其他编码。我认为您需要用一个示例来说明您正在尝试做什么。我只需要资源中的$id。有可能吗?我不这么认为。这就是为什么这可能是一个XY问题(询问您的解决方案,而不包括问题本身)您可以在将所需的项传递给资源集合之前查询它们,这可能是最好的处理方法。资源类并不是真正设计用来处理大量逻辑的。
<?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);
}
}