Shokouh Dareshiri
Shokouh Dareshiri

Reputation: 936

Join multi create in Laravel?

I would like to insert new records in 3 Tables at once. Is there any solution to use one create or join three tables?

In SingleController.php:

$single = Single::create([
                    'structure_id' => $request->structure_id,
                    'user_id' => auth()->id(),
                ]);

$structure = Structure::create([
                    'name' => $request->name,
                ]);

$placement = Placement::create([
                    'structure_id' => $request->structure_id,
                    'seed' => $request->seed,
                ]);

In model of Structure.php :

public function singles()
{
    return $this->hasMany(Single::class);
}

public function placements()
{
    return $this->hasMany(Placement::class);
}

Upvotes: 0

Views: 25

Answers (1)

Manzurul Hoque Rumi
Manzurul Hoque Rumi

Reputation: 3094

After creating Structure you could do like this:

$structure->singles()->create({
    'structure_id' => $request->structure_id,
    'user_id' => auth()->id(),
})

$structure->placements()->create({
    'structure_id' => $request->structure_id,
    'seed' => $request->seed,
})

Follow the Docs

Upvotes: 1

Related Questions