skip to Main Content

In my Contact model, I’m trying to type hint a service class:

use AppServicesContactService;
class Contact extends Model
{
    /**
     * @var AppServicesContactService
     */
    protected $contactService;

    public function __construct(ContactService $contactService)
    {
        $this->contactService = $contactService;
    }
}

use AppServicesCRMCRMService;
class ContactService
{
    public function __construct(protected CRMService $crmService)
    {}
}

I’m getting this error:

Too few arguments to function AppModelsContact::__construct(), 0 passed in

The error happens when I call $dealer->contacts

public function contacts()
{
   return $this->hasMany(AppModelsContact::class, 'dealer_id');
}

I thought the $contactService should be injected automatically and I shouldn’t be including it manually. What am I missing?

2

Answers


  1. Chosen as BEST ANSWER

    Based on the comments and answers, I ended up changing my Contact's model constructor to this and it's working great:

    use AppServicesContactService;
    
    class Contact extends Model
    {
        public function __construct()
        {
            $this->contactService = app(ContactService::class);
        }
    } 
    

    Thanks!


  2. Try this in Dealer class

    public function contacts()
    {
        return $this->hasMany(
            AppModelsContact::class, 
            'dealer_id'
        )->setFactory(function ($attributes) {
            return app(Contact::class, [
                'contactService' => app(ContactService::class)
            ]);
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search