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
My Answer:
php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CategoryResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
// other attributes
];
}
}
Resources in Laravel are used to transform models into JSON responses. They are great for separating the presentation logic from the controller and keeping your code clean and organized.
On the other hand, ViewModels are a design pattern that is used to separate the presentation logic from the business logic. They are used to encapsulate the data and behavior of a view, making it easier to manage and test.
In your case, since you are already using Resources in your Laravel application, you can continue using them for transforming your models into JSON responses. However, if you find that your presentation logic is becoming too complex or tightly coupled with your models, you may consider using ViewModels to separate the concerns and make your code more maintainable.
Overall, both Resources and ViewModels have their own advantages and use cases, so it ultimately depends on your specific requirements and preferences.
Rate this post
4 of 5 based on 7915 votesComments