Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bacordioroger's avatar

Saving to Two Models

How to save to two models related to school?

School Model

    public function schedules(){
        return $this->hasMany(Schedule::class);
    }

    public function toys(){
        return $this->hasMany(Toy::class);
    }

Schedule Model

    public function schools_schedules(){
        return $this->belongsTo(School::class);
    }

Toy Model

    public function schools_toys(){
        return $this->belongsTo(School::class);
    }

Controller:

        $school = new School;
        $school->firstOrCreate(['school' => request('school')],
        [
            'address' => request('address'),
            'contact' => request('contact'),
            'email' => request('email'),
            'facebook' => request('facebook'),
            'level' => request('level'),
            'students' => request('students'),
        ])->schedules()->create([
            'date' => request('date'),
            'started' => request('started'),
            'finished' => request('finished')
        ])->toys()->create([
            'toys' => request('toys'),
            'tubs' => request('tubs'),
            'assorted' => request('assorted')
        ]);

Error: Call to undefined method App\Schedule::toys()

0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

The relationship is on School, not on Schedule (which was returned from the ->schedules()->create(...)` call. Chaining in this way is not clever IMHO; it obfuscates what is happening:

$school = School::firstOrCreate([
    'school' => request('school')
], [
    'address' => request('address'),
    'contact' => request('contact'),
    'email' => request('email'),
    'facebook' => request('facebook'),
    'level' => request('level'),
    'students' => request('students'),
]);

$school->schedules()->create([
    'date' => request('date'),
    'started' => request('started'),
    'finished' => request('finished')
]);

$school->toys()->create([
    'toys' => request('toys'),
    'tubs' => request('tubs'),
    'assorted' => request('assorted')
]);

Please or to participate in this conversation.