0

I have model Object with relationship:

 public function category(){
   return $this->hasOne('App\FieldCategoriesValues');
 }

How to add new value to category?

I tried:

$object = new Object();
$object->category()->save(["id" => 4])

It does not work.

1
  • You should probably use the create() method instead of save() for saving directly from an assoc array - as described in the docs: laravel.com/docs/5.4/… Commented May 4, 2017 at 14:20

1 Answer 1

1

In order to save the relationship the first model needs to be created before creating/saving the second model. You can check for existence of a mode with the $exists attribute.

Also, you pass a model to a relationship's save() method and an array to create().

For example for the parent model:

$object = new Object;
$object->exists; // false
$object->save();
$object->exists; // true

OR

$object = Object::create();
$object->exists; // true

Then you can save the related model as:

$category = new Category(["id" => 4]);
$object->category()->save($category);

OR

$category = $object->category()->create(["id" => 4]);
Sign up to request clarification or add additional context in comments.

2 Comments

Can I delete like as: $category = $object->category()->delete(["id" => 4]);
Since you're working with a hasOne relationship $object->category will return a model so you can do $object->category->delete();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.