提问者:小点点

如何使用Laravel资源筛选数组中的对象


我有一个practice Laravel应用程序,显示培训课程。 为了让它更容易使用,我想使用分类,所以如果你想看烹饪课程你可以点击'/categories/Cooking',看到所有的烹饪课程。

所以我建立了我的模型,表格和关系。 如果我跑:

返回category::with('courses')->where('slug','=',$slug)->firstorFail();

我得到:

[
    {
        "id": 1,
        "title": "Course 5",
        "description": "Ipsa ad quae optio dolorum et nesciunt nulla. Libero illum a quam provident alias sapiente. Omnis debitis quasi eius nihil enim. Ut saepe explicabo hic est rerum molestiae est. Iusto voluptatem aut non voluptatem qui fuga inventore. Et sit blanditiis amet fugit doloremque.",
        "cost": 1209,
        "slug": "autem-aspernatur-rerum-cumque-commodi-est-et",
        "category_id": 5,
        "created_at": "2020-06-16T13:09:56.000000Z",
        "updated_at": "2020-06-16T13:09:56.000000Z",
        "short_description": "Quod odit nam quisquam ab sint.",
        "length": 1,
        "pivot": {
            "category_id": 2,
            "course_id": 1
        }
    },
    {
        "id": 2,
        "title": "Course 3",
        "description": "Veniam voluptates velit veniam eum distinctio eum praesentium sed. Ad molestiae ea voluptatem aut velit ab. Voluptatum non ut facilis autem ducimus excepturi. Sit eum aperiam aut eos.",
        "cost": 1077,
        "slug": "iusto-doloremque-repellat-repellat-illo-rerum-libero",
        "category_id": 5,
        "created_at": "2020-06-16T13:09:56.000000Z",
        "updated_at": "2020-06-16T13:09:56.000000Z",
        "short_description": "Sint dolores omnis aut repudiandae quis.",
        "length": 1,
        "pivot": {
            "category_id": 2,
            "course_id": 2
        }
    }
]

现在,显然我不希望所有这些都用于我的视图,因为用户只是在选择一个课程。 我只需要标题和鼻涕虫。 所以我做了一个资源来过滤一切:

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'course_title' => $this->courses->title,
            'course_slug' => $this->courses->slug
        ];
    }

在控制器中:

return new CategoryShowResource(Category::with('courses')->where('slug','=',$slug)->get());

但这会引发一个例外:

"message": "Property [id] does not exist on this collection instance.",

然后我突然想到课程在一个阵列中。 所以如果我做了:

 $category = Category::with('courses')->where('slug','=',$slug)->firstOrFail();
 return $category->courses[0]->title;

果不其然,我只是

Course 5

问题是,如何使用资源过滤我想要的东西,因为它似乎不想很好地发挥课程数组?


共1个答案

匿名用户

尝试先获取类别,然后将课程传递到收集功能

$category = Category::with('courses')->where('slug','=',$slug)->get();
return CategoryShowResource::collection($category->courses);