ignaciodev's avatar

Multiple relationships on model create() without ids being fillable.

I have a question about relationships ids.

I know that if I want a 'user_id' field , I can do something like $user->posts()->create() and the user_id will be there automatically.

But what if there are other relationships? For example $order->items()->create(['product_id']). Is there some sort of method to do this?

Maybe something like $order->items()->forProduct($product)->create() ?

Or do I need to make that product_id fillable?

Thank you!

0 likes
3 replies
LaryAI's avatar
Level 58

One solution would be to pass an array of attributes to the create() method, including the foreign key values for any related models. For example:

$product = Product::find(1);
$order->items()->create([
    'product_id' => $product->id,
    'quantity' => 1,
]);

If you don't want to make the foreign key attributes fillable, you can use the associate() method to set the related model before calling create(). For example:

$product = Product::find(1);
$item = new Item(['quantity' => 1]);
$item->product()->associate($product);
$order->items()->save($item);

This sets the product_id attribute on the Item model without making it fillable.

Snapey's avatar
Snapey
Best Answer
Level 122

No, no special method. You have to assign other related model keys explicitly.

So, yes, if you are using mass assignment methods then the foreign key needs to be fillable

2 likes

Please or to participate in this conversation.