在 lumen 8 应用程序中,我使用资源并在此处阅读 https://laravel.com/docs/8.x/eloquent-resources
我尝试使用“with”方法,因为我想向任何请求添加一些元数据,而返回的数据中没有这些元数据:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Models\Page As PageModel;
use App\Http\Resources\User as UserResource;
class Page extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
...
'created_at' => $this->created_at,
];
}
public function with($request)
{
\Log::info( '-1 unction with ::' . print_r( 1, true ) ); // I DO NOT SEE THIS LOGGINHG line
return [
'meta' => [
'version'=>getAppVersion()
]
];
}
}
在引用的文档中,资源声明与 ResourceCollection 有点不同:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
public function toArray($request)
{
return parent::toArray($request);
}
public function with($request)
{
return [
'meta' => [
'key' => 'value',
],
];
}
}
这可能是问题吗?如何修复我的资源以获取所有元数据?
更新块: UserCollection - 即集合https://laravel.com/docs/8.x/eloquent-resources 我的集合是 Page,我在控制器中将其用作:
namespace App\Http\Controllers;
use Carbon\Carbon;
use App\Models\Page;
use Illuminate\Http\Request;
use App\Http\Resources\Page as PageResource;
use Config;
use App\Http\Requests\PageRequest;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Validator;
class PageController extends Controller
{
public function index()
{
$pages = Page
...
->get();
return $this->sendOkResponse(PageResource::collection($pages), '');
}
sendOkResponse 在 Http/Controllers/Controller.php 中定义:
class Controller extends BaseController
{
protected $requestData;
public function __construct()
{
$request = request();
$this->requestData = $request->all();
}
public function sendOkResponse($responseResult, $message)
{
$response = [
'success' => true,
'data' => $responseResult,
'message' => $message,
];
return response()->json($response, HTTP_RESPONSE_OK);
}
我想 PageResource 在 PageController 控制器索引方法退出时被销毁...
更新块#2: 经过一些测试,我发现如果返回集合,资源方法“with”不起作用,我需要在控制器中使用 ->additional,例如:
return (PageResource::collection($pages))
->additional([
'meta' => [
'version' => getAppVersion()
]
]);
但是在我返回 sinopgle 元素(ex store 方法)的情况下
return (new PageResource($page));
“with”方法工作正常。
这不包括使用像 sendOkResponse 这样的包装器。是唯一正确的方法吗?
提前致谢!