我想知道是否有一种方法可以检查后端(Laravel)是否请求(例如 GET/posts)来自 Inertia 前端或其他来源(例如 Postman API)。
目前看来,如果我想为共享路由创建一个公共(public) API(例如 Posts 模型的 CRUD),我必须创建单独的路由,因为 Controller 返回一个服务器端渲染的 Vuejs 组件。
有没有办法做这样的事情:
public function index()
{
$this->authorize('viewAny', Post::class);
if(request()->isInertiaRequest()) { //<- check if the request is API or Vuejs Inertia frontend
return inertia('Posts/Index', [
'posts' => PostResource::collection($this->postService->index()),
]);
}
return PostResource::collection($this->postService->index());
}
我觉得编写单独的 API 和 Inertia 路由会违背 DRY,因为返回的数据将是相同的资源。
最佳答案
以下代码行将检查请求是否来自适用于您的情况的 API
if(!$request->inertia() && $request->expectsJson())
关于Laravel Inertia - 检查请求是否来自 Intertiajs 组件或 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75933904/