DEV Community

Discussion on: How to implement Clean Architecture with Laravel

Collapse
tiagodevweb profile image
Tiago Lopes

Congratulations for the post, my question is in the case of a REST API, the viewmodel would be needed? If not what would be the default return type for presenter methods?

Collapse
bdelespierre profile image
Benjamin Delespierre Author • Edited on

I believe in the case of REST API, the ViewModel would be a Laravel Resource wrapper:

class CreateUserJsonPresenter implements CreateUserOutputPort
{
    public function userCreated(CreateUserResponseModel $model): ViewModel
    {
        return new JsonResourceViewModel(
            new Resources\UserCreatedResource($model->getUser())
        );
    }

    public function userAlreadyExists(CreateUserResponseModel $model): ViewModel
    {
        return new JsonResourceViewModel(
            new Resources\UserAlreadyExistsResource($model->getUser())
        );
    }

    public function unableToCreateUser(CreateUserResponseModel $model, \Throwable $e): ViewModel
    {
        if (config('app.debug')) {
            // rethrow and let Laravel display the error
            throw $e;
        }

        return new JsonResourceViewModel(
            new Resources\UnableToCreateUserResource($e)
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

I'll update the reference project with examples for a REST API and write another article about it. Stay tune!