I'm starting to work on an API service with Laravel. Now, I'm using a DDD approach (and learning it at the same time).
Currently my structure looks like this:
MyApp
- app
- (laravel app stuff)
- src
- Domain
- Category
- Actions
- DataTransferObjects
- Models
- Resources
- Category
- Domain
As you can see I'm currently using Resources
. So for example, in my Categories' controller I've got:
public function index(): AnonymousResourceCollection
{
$categories = Category::all();
return CategoriesResource::collection($categories);
}
and my resource file looks like this:
<?php
namespace Domain\Category\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class CategoriesResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param Request $request
* @return array
*/
public function toArray($request): array
{
return [
'id' => (string)$this->id,
'type' => 'categories',
'attributes' => [
'name' => $this->name,
'parent' => $this->parent,
'description' => $this->description,
'image' => $this->image,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]
];
}
}
which returns the JSON response that will be eventually expected by the frontend.
Now, I've been reading about ModelView
but still don't understand the concept or how could it work instead of (or along with) Resources
. Most of the examples I've seen so far don't actually return a whole JSON response from the ModelView
.
Thanks