Creating Instance Of Eloquent With Multiple Relationships?

I have 3 models: Plugin, Review and User.

The User is the parent of Plugin. At a one-to-many relationship I can create a plugin asociated with the user easily:


But now my problem is: A Review is the child of both User and Plugin. How to create a review with the User and the Plugin without setting one ID manually?



Assuming that a Review belongsTo a User and a Plugin, you can use the associate() method of the relationship to set the foreign keys. Note, this method only sets the proper attribute on the object; you still have to save() the object to update the database.

Here is an example:

$plugin = $user->plugins()->create([...plugin options...]);

// instantiate a new review instance
$review = new \App\Review([ options...]);

// set the user association

// set the plugin association

// save the entire record to the database