Connor Simpson
Connor Simpson

Reputation: 487

Create nested relationships in Laravel

I've been trying to discover whether or not it's currently possible to do the following.

Basically I have three models: Customer, Invoice, and Unit. (Customer has one Invoice; an Invoice has many Units).

I was wondering if it was possible to seamlessly do the following:

...

# Let's pretend that further up the code that
# Customer has all the properties set and now
# being saved in the database.

$Customer->save();

# This is currently trying set the values of
# 'units' to a non-existent table column in 
# 'invoices' table.

$Customer->invoice()->create([
    "units" => [
        [
            "name" => "Unit 1",
            "amount" => 999.99,
            "tax" => "20%",
            "type" => "+"
        ]
    ]
]);

Upvotes: 0

Views: 787

Answers (2)

If you setup the relationships in the model as you described them, then you can achieve it close to what you've shown. Something like this:

Customer

public function invoice()
{
    return $this->hasOne(Invoice::class);
}

Invoice

public function units()
{
    return $this->hasMany(Unit::class);
}

Then calling:

$customer->invoice()->units()->create([
    "name" => "Unit 1",
    "amount" => 999.99,
    "tax" => "20%",
    "type" => "+"
]);

Should work.

if you call save on the invoice first, then you should just call $invoice->units()

$invoice = $customer->invoice()->create([
    "campany" => "Unit 1",
    "dat" => "2022-02-18"
]);

$invoice->units()->create([
    "name" => "Unit 1",
    "amount" => 999.99,
    "tax" => "20%",
    "type" => "+"
]);

... instead of doing it through the Customer. so $invoice = $customer->invoice()->create(...); before, and then add units.

Upvotes: 0

nakov
nakov

Reputation: 14268

If you setup the relationships in the model as you described them, then you can achieve it close to what you've shown. Something like this:

Customer

public function invoice()
{
    return $this->hasOne(Invoice::class);
}

Invoice

public function units()
{
    return $this->hasMany(Unit::class);
}

Then calling:

$customer->invoice()->units()->create([
            "name" => "Unit 1",
            "amount" => 999.99,
            "tax" => "20%",
            "type" => "+"
        ]);

Should work.

Upvotes: 3

Related Questions