如何在 laravel 的自定义资源中检索 Spatie 媒体集合?

分享于2022年07月17日 laravel laravel-medialibrary php 问答
【问题标题】:如何在 laravel 的自定义资源中检索 Spatie 媒体集合?(how to retrive Spatia media collection in custom resource in laravel?)
【发布时间】:2022-06-23 17:07:44
【问题描述】:

我在 laravel 中使用 Spatie 媒体包,当我尝试在 Spatie 集合中显示媒体时,显示包中的默认数据。

控制器:

 public function index(IndexTicketRequest $request)
{
    $tickets = Ticket::query()->with(['employee','media']);

    if ($request->has('status')) {
        $tickets->where('status', $request->get('status'));
    }

    return TicketResource::collection($tickets->orderByDesc('created_at')->paginate($request->per_page ?? 20));
}

资源:

 public function toArray($request)
{

    return [
        'id' => $this->id,
        'category' => $this->category,
        'fullname' => $this->fullname,
        'username' => $this->username,
        'file' => $this->file,
        'message' => $this->message,
        'status' => TicketType::getDescription($this->status),
        'employee' => $this->whenLoaded('employee'),
        'media' => $this->whenLoaded('media'),
    ];
}


【解决方案1】:

加载带有集合的媒体非常简单。您只需要在分页之前添加 with 函数(例如: with(['media']) )。请遵循修改:

    public function index(IndexTicketRequest $request)
    {
        $tickets = Ticket::query()->with(['employee','media']);

        if ($request->has('status')) {
            $tickets->where('status', $request->get('status'));
        }

        return TicketResource::collection($tickets->orderByDesc('created_at')->with(['media'])->paginate($request->per_page ?? 20));
    }