I'm trying to build an app in Laravel 5.3, I want to add additional column data in the pivot table. Following is my code:
My Users
model:
public function relations()
{
return $this->belongsToMany('App\Plan')->withPivot('child');
}
My Plan
model:
public function relations()
{
return $this->belongsToMany('App\User')->withPivot('child');
}
In my controller I'm fetching the user data from Auth::user();
and for plans and child element I'm getting through request. I want to store this to my pivot table. Following is the code which I tried in my controller:
$user = \Auth::user();
$plan_id = $request->plan_id;
$childid = $request->child_id;
$plan = App\Plan::find($plan_id);
$user->relations()->attach($plan, ['child' => $childid]);
Help me out in this.
There are many ways to update the pivot table in Laravel. We can use attach(), detach(), sync(), and pivot attribute to update the intermediate table in Laravel.
On the relationships for both User and Target , tack on a ->withPivot('type') which will instruct Laravel to include that column. Then once you have your result set, you can access the field with $user->pivot->type .
In laravel, When working in a many-many relationship, the user has to choose the intermediate table and it is called a pivot table in terms of Laravel. The pivot attribute communicates with this intermediate table in controllers or models in Laravel. The admin in laravel has to define the role of every other user.
Pivot Table with Extra Columns in Laravel To get data from pivot table: By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:
How to Add a Column in Pivot Table 1 Open the Excel file with the pivot table you want to edit. 2 Click any cell on the pivot table. 3 Click the Pivot Table Analyze tab at the top. 4 Click the Field List button on the toolbar ribbon. 5 Check the box next to any item on the FIELD NAME list. 6 ... (more items) See More....
You must first save the post (so that laravel knows what ID to add to the pivot table for post_id) and then add the relations. If you are worried about the tags part failing and then having an inconsistent database you should use transactions.
Using the Pivot Table Tools Click on the PivotTable. This will open the Field List. Click the checkbox next to the field you want to add. Typically non-numeric fields are added automatically to rows, and numeric fields are added to columns by default. Change the field properties if needed.
You should use attach()
like this:
$user->relations()->attach($plan_id, ['child' => $childid]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With