Ad

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:

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

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?

Ad

Answer

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([...review options...]);

// set the user association
$review->user()->associate($user);

// set the plugin association
$review->plugin()->associate($plugin);

// save the entire record to the database
$review->save();
Ad
source: stackoverflow.com
Ad