CurtisUpshall
CurtisUpshall

Reputation: 75

Laravel Model creation override

In my Laravel project, I have different user types that all have a base User model. Here's a brief idea of the database topology:

users:
 - id
 - name
 - email

students:
 - age
 - user_id

teachers:
 - budget
 - user_id

employee:
 - is_admin
 - user_id

In my case, each of Student, Teacher, Employee has their own User. But if I want to make a new Student for example, I have to make both a Student and User model. I'm aware of the Observers pattern in Laravel which can make this job easier, but I'd like to be able to programatically make Student models like the following:

$student = App\Student::create(['name' => 'Joe', 'email' => '[email protected]', 'age' => '20']);

The problem gets even more complex from there, because Teacher models are also required to have both an Employee model and a User model. Is there a way to override the create method on my model so that I can pass in User creation parameters, but also Student parameters?

Upvotes: 0

Views: 956

Answers (1)

omar jayed
omar jayed

Reputation: 868

You can override the create method and do this yourself. In your Student model class add this:

public static function create($arr) {
    $user = User::create([
        'name' => $arr['name'],
        'email' => $arr['email']
    ]);

    $student = parent::create([
        'age' => $arr['age']
        'user_id' => $user->id
    ]);

    return $student;
}

You can do other methods in a similar way.

If you Laravel version is above 5.4.* do this instead:

public static function create($arr) {
    $user = User::create([
        'name' => $arr['name'],
        'email' => $arr['email']
    ]);

    $student = static::query()->create([
         'age' => $arr['age']
         'user_id' => $user->id
    ]);

    return $student;
}

Upvotes: 1

Related Questions