If you are going to use the current user id to save it on the database: yes.
In your case, as you already send the user instance as an argument to the CreatePostAction's execute method, and ends not using the $dto->userId property: no.
Hello,
I have some doubts on how to make this approach.
Imagine a blog like an user create some post.
PostsController
public function store()
{
// validate the request...
$post = app(CreatePost::class)->execute(auth()->user(), PostDTO:fromRequest());
return response()->json(...);
}
PostDTO
class PostDTO
{
public function __construct(
public readonly ?int $userId = null, // omit this because it does not "belongs" here
public readonly string $title,
public readonly string $body,
// ...
)
}
CreatePostAction
class CreatePostAction
{
public function execute(User $user, PostDTO $dto)
{
return $user->posts()->create(['title' => $dto->title, 'body' => $dto->body]);
}
}
My question is: would you pass the user (or the user Id) to the DTO or not?
Please or to participate in this conversation.