'How do i properly create a new model, fill the fillable fields and then save the relationship?

I think i didn't get the right method to create and save a new model:

$newSelling = Selling::create([
    'code'  => $this->code,
    'date'  => $this->date,
]);

$newSelling->customer()->save(Customer::find($this->customer_id));

And i get this error:

General error: 1364 Field 'customer_id' doesn't have a default value

The field customer_id is the belongsTo key to Customer::class



Solution 1:[1]

There is a tip: The most internal function is execute

So first, find function of Customer model, will be execute. in this function there is a parameter that refer to customer_id of this object of class

Customer::find($this->customer_id) return null. because there isn't exist the customer with this id or $this->customer_id might been empty

So in save method parameter there is a null parameter. thus this error occured. because there isn't exist any customer with $this->customer_id id.

If you want to see, write dd(Customer::find($this->customer_id)) in your code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniyal Sedighpour