Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent: Model relationship without saving to DB

Say I have two Models: User and Task

Their relationship is as follows: User can have many tasks (belongsToMany) Task can have many users (belongsToMany)

$user = new User();
$task = new Task();

Normally, I'd do something like this: $user->tasks->attach($task)

But the problem is the User and Task is not persisted in the database. So if I run the last code above, I'll get an integrity constraint because these models have no id.

I have looked into the documentation and I found at that there is a method associate() but this requires either one of the model that has an id (saved in the database).

Is there any way I could attach a Model to another Model without them having persisted in the database?

like image 852
John Aldrin Avatar asked Jan 01 '26 19:01

John Aldrin


2 Answers

I guess you could call setRelation manually.

$model->setRelation('child', $childInstance);

eLSE

You create a new model simply by instantiating it:

$model = new Model;

You can then save it to the database at a later stage:

$model->save();
like image 109
Arun Ganessh Avatar answered Jan 03 '26 10:01

Arun Ganessh


You can use the make method on the relation itself to create a relation model instance without saving. The make method is not part of the docs but part of the Laravel API Docs.

Example:

$task = $user->tasks()->make($attributes);

If you would like to persist $task afterwads you can save the task with the save method.

$task->save();

Source:

make(array $attributes = [])

Create and return an un-saved instance of the related model.

https://laravel.com/api/11.x/Illuminate/Database/Eloquent/Relations/HasMany.html

like image 29
Linus Avatar answered Jan 03 '26 12:01

Linus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!