bildy
2 months ago
251
9
Laravel

Store morphed model

Posted 2 months ago by bildy

I have Task and Customer models both of which can have comments, therefore I have morphed Comment model. I'm using CommentController to store data but I feel like I have to repeat myself in this code:

    private function storeMorphedComment($model)
    {
        $comment = $model->comments()->create(request()->all());

        // response
    }

    public function storeTaskComment(Task $task)
    {
        return $this->storeMorphedComment($task);
    }

    public function storeCustomerComment(Customer $customer)
    {
        return $this->storeMorphedComment($customer);
    }

It's working. But it's ugly? Is there a better solution? I'm looking to replace storeXXXComment methods with one method, something like this:

    public function store(AnyModel $model)
    {
        $comment = $model->comments()->create(request()->all());
        // ...
    }

Or maybe somehow without autowiring?

Please sign in or create an account to participate in this conversation.