Search code examples
laravelmodeleloquentlaravel-5.3relationship

Laravel5.3 - Create certain number of related models - when a model is created


I have two models:

Model1 with relationship:

public function model2()
{
    return $this->hasMany('App\Model2');
}

Model2 with relationship:

public function model1()
{
    return $this->belongsTo('App\Model1');
}

I need to create a certain number (4) of Model2's with different kind of settings(so, not random Models2, just related to Model1), when the Model1 is created. It is important to be able to access the Model1's parameters, when creating the Model2's. Is there any elegant/automatic way? My first idea was to create a method for the Model1, but I suspect there is a more elegant way.


Solution

  • You can use created event for the first model.

    https://laravel.com/docs/5.3/eloquent#events

    Events allow you to easily execute code each time a specific model class is saved or updated in the database.