Laravel API仅获取帖子类别

时间:2019-06-02 07:13:14

标签: php laravel api

我有API资源,可以在我的API控制器中调用它,以便它返回我的数据,我需要在此API中添加一个额外的过滤器,但不确定如何?

我需要什么

  1. 获取仅具有帖子的类别。
  2. 排除类别而不发布结果。

我有什么

  1. 列出所有带有和不带有帖子的类别。

代码

Resource

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\PostResource;

class CategoryResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'image' => url('images', $this->photo),
            'url' => $this->slug,
            'posts' => PostResource::collection($this->whenLoaded('posts')),
            'created_at' => (string) $this->created_at,
            'updated_at' => (string) $this->updated_at,
        ];
    }
}

Controller

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryResource;
use App\Category;

class CategoryController extends Controller
{
    public function index(){
        $categories = CategoryResource::collection(Category::where('status', '1')->with('posts')->orderby('id', 'desc')->get());
        return response()->json($categories);
    }
}

是否知道如何在我的控制器中添加该过滤器?

1 个答案:

答案 0 :(得分:2)

您可以使用html { scroll-behavior: smooth !important; } 函数过滤至少有一篇帖子的类别,如下所示:

has