Showing data for a chat with another user I have a get route to show the data for a chat with another user. If an existing chat exists I want to return that, otherwise create a new chat and return it.

/chat/user/{contra_user_id}


Should my Service or my repository be adding chat members to the chat? Currently I have my service creating each member.

class ChatService
{
    private $chatRepository;

    public function __construct(ChatRepository $chatRepository)
    {
        $this-&gt;chatRepository = $chatRepository;
    }

    public function findByUsers(User $user, User $contraUser) : Collection
    {
        $chat = $this-&gt;chatRepository-&gt;findByUsers($user, $contraUser);
        if ($chat = $chat-&gt;first()) {
            return $chat;
        }

        $chat = $this-&gt;chatRepository-&gt;create();
        $member = $this-&gt;chatMemberRepository-&gt;create($chat, $user);
        $contraMember = $this-&gt;chatMemberRepository-&gt;create($chat, $user);
        $returnChat = $this-&gt;chatRepository-&gt;find($chat-&gt;id);

        return $returnChat;
    }
}
You can break the functionality in to 2 seperate methods to make it more reusable. Here, findChatByUsers could return a collection or null, so the type hint was removed.

public function findChatByUsers(User $user, User $contraUser)
{
    $chat = $this-&gt;chatRepository
        -&gt;findByUsers($user, $contraUser)
        -&gt;first();

    return $chat;
}

public function getChat(User $user, User $contraUser) : Collection
{
    $chat = $this-&gt;findChatByUsers($user, $contraUser);

    // If chat is not available, create new chat
    if (!$chat) {
        $chat = $this-&gt;chatRepository-&gt;create();
        $member = $this-&gt;chatMemberRepository-&gt;create($chat, $user);
        $contraMember = $this-&gt;chatMemberRepository-&gt;create($chat, $user);
        $chat = $this-&gt;chatRepository-&gt;find($chat-&gt;id);
    }

    return $chat;
}