I have a model, let’s say this a Task model. It has title
, description
, and status_id
.
I want to make a resource model to format the status, so the frontend (just a simple blade) can use it.
So, I made a resource collection, like this:
class TaskResource extends JsonResource
{
public function toArray(Request $request): object
{
return (object) [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'status' => (object) [
'id' => $this->status_id,
'display' => TaskStatus::tryFrom($this->status_id)?->text(),
],
];
}
}
… and I do this in my controller
public function show(Task $task)
{
return view('tasks.show', ['task' => new TaskResource($task)]);
}
So, I can access $task
in my blade – but the problem is, status
, nor the id
inside status
are accessible. Like they don’t exist. Even if I do something like this:
'title' => $this->title,
'random' => $this->title,
then $task->title
returns the title, but $task->random
will show nothing.
I do not want to call ->toArray(request())
everywhere, every single time on the new resource, also there’s no reason for me to pass the request
every single time (tho I can’t update it to not make it required, because of the built-in interface).
I also don’t want to use laravel magic, like “getStatusDisplayAttribute” and such, because laravel magic is for sure useful, but is hard to maintain on a larger scale.
A “workaround” I found as a possible solution is resolve
, which works with both TaskResource::collection
and (new TaskResource())
.
return view('tasks.show', ['task' => (new TaskResource($task))->resolve()]);
But is this a good practice? Or there’s a different way people format the data as needed on the backend, before passing it to the frontend?
I want to make sure I don’t make many bad decisions while learning.