Search code examples
phplaravelrelationshiplaravel-5.5has-many

Eloquent relationship and class with constructor


I have two classes which are connected through hasMany and belongsTo method.

class InquiryParameter extends Model
{
    public function translations()
    {
        return $this->hasMany(InquiryParameterTranslation::class);
    }
}

class InquiryParameterTranslation extends Model
{
    public function __construct($inquiry_parameter_id, $language_code, $name, $description)
    {
            $this->inquiry_parameter_id = $inquiry_parameter_id;
            $this->language_code = $language_code;
            $this->name = $name;
            $this->description = $description;
    }
}

However, when I create new object

$inquiry_parameter = new InquiryParameter;

And then call method translations.

$names = $inquiry_parameter->translations;

I received error:

Type error: Too few arguments to function App\InquiryParameterTranslation::__construct(), 0 passed in /Users/SouL-MAC/Code/konfig/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php on line 653 and exactly 4 expected (View: /Users/SouL-MAC/Code/konfig/resources/views/admin/inquiry/parameters.blade.php)

Is it possible to use eloquent relationship with classes which contains constructor ? Or am I doing something wrong ?

Thanks for your replies


Solution

  • $names = $inquiry_parameter->translations;

    When above code runs, it actually creates a new object of Class InquiryParameterTranslation without passing any parameters to constructor. But your constructor expects parameters. Therefore it is causing error.

    Solution to this problem is that you change your constructor code as given below:

    public function __construct()
    {
        // no parameter in constructor
    }
    

    Then create another function (as given below) to initialize model properties

    public function initialize($inquiry_parameter_id, $language_code, $name, $description)
    {
            $this->inquiry_parameter_id = $inquiry_parameter_id;
            $this->language_code = $language_code;
            $this->name = $name;
            $this->description = $description;
    }
    

    By making above changes your code will run fine and when you need to add new translation to database you can use following code (Example)

    $translation = new InquiryParameterTranslation;
    $translation->initialize($inquiry_parameter_id, $language_code, $name, $description);
    
    $translation->save();