Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aminbaig's avatar

How do I insert user id in an associative table?

I have three table, campaign, places and campaign_place, the primary keys in campaign and place are used inside campaign_place as foriegn keys plus the campaign_place table has it's own id column and the user_id column.

I have setup the proper many to many relationships using BelongsToMany in campaign and place models.

1- I define a number of places, and then I go and create a campaign. I have a multi select box which is populated by the places created by the logged in user.

2- What I am trying to achieve is that when I save the campaign the places selected in the multiselect are also saved in the associative table with user_id.

currently I am successfully saving all the data in campaigns, places and in the associative table of campaign_place as well.

The only thing I am confused about is saving the user_id in the associative table as well because at this time its not being saved.

Following is the code:

Create form for campaigns:

{!! Form::open(array('route' => 'campaigns.store')) !!}

                        {{Form::label('campaignName','Campaign Name:' )}}
                        {{Form::text('campaignName', null, array('class' => 'form-control', 'placeholder'=>'Name of your campaign')) }}

                        {{Form::label('campaignDescription','Campaign Description:' )}}
                        {{Form::textarea('campaignDescription', null, array('class' => 'form-control', 'rows' => '2', 'placeholder'=>'Provide a small description of your campaign...')) }}

                        <div class="col-lg-6">

                            {{Form::label('startDate','Start Date:' )}}
                            {{Form::date('startDate', null, array('class' => 'form-control')) }}

                        </div>

                        <div class="col-lg-6">
                            {{Form::label('endDate','End Date:' )}}
                            {{Form::date('endDate', null, array('class' => 'form-control')) }}
                        </div>

                        {{Form::label('title','Campaign Title:' )}}
                        {{Form::text('title', null, array('class' => 'form-control', 'id' => 'title','placeholder'=>'This will appear in your mobile')) }}

                        {{Form::label('places','Assign Places:' )}}
                        <select class="form-control select2-multi" name="places[]" multiple="multiple">
                            @foreach (auth()->user()->places as $place)
                                <option value='{{ $place->id }}'>{{ $place->name }}</option>
                            @endforeach
                        </select>

                        {{Form::label('notificationText','Notification Text:' )}}
                        {{Form::text('notificationText', null, array('class' => 'form-control')) }}

                        {{Form::label('body','Campaign Body:' )}}
                        {{Form::textarea('body', null, array('class' => 'form-control', 'rows' => '3')) }}

                        {{Form::hidden('user_id', Auth::user()->id)}}


                        {{Form::submit('Save Campaign', array('class' => 'btn btn-success btn-lg btn-block', 'style' => 'margin-top: 20px;'))}}

                        {!! Form::close() !!}

Code for the models:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Campaign extends Model
{
    protected $fillable=['user_id','campaignName','campaignDescription','startDate','endDate','title','notificationText','body'];

    public function places()
    {
        return $this->belongsToMany('App\Place');
    }
}

Place model:


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Place extends Model
{
    protected $fillable=['name','description','ownedssid','ownedmacaddress', 'ownedrssival', 'lat', 'lng','gfenceradius','country','city','citycode'];

    public function campaigns()
    {
        return $this->belongsToMany('App\Campaign');
    }


}

Code for store function in campaign controller:

    public function store(Request $request)
    {
        // dd($request);

        $this->validate($request, array(
            'campaignName' =>'required|max:255',
            'startDate'    =>'required',
            'endDate'      =>'required',
            'title'      =>'required',
            'notificationText'      =>'required',
            'body'          =>'required'

        ));
        $user = Auth::user();
        $campaign = new Campaign;

        $campaign->campaignName = $request->campaignName;
        $campaign->campaignDescription = $request->campaignDescription;
        $campaign->startDate = $request->startDate;
        $campaign->endDate = $request->endDate;
        $campaign->title = $request->title;
        $campaign->notificationText = $request->notificationText;
        $campaign->body = $request->body;
        $campaign->user_id = $request->user_id;


        $campaign->save();
        $campaign->places()->sync($request->places, false);

    }

Can you please help!

thanks in advance

0 likes
9 replies
aminbaig's avatar

code for the store function in campaign controller is:

public function store(Request $request)
    {
        // dd($request);

        $this->validate($request, array(
            'campaignName' =>'required|max:255',
            'startDate'    =>'required',
            'endDate'      =>'required',
            'title'      =>'required',
            'notificationText'      =>'required',
            'body'          =>'required'

        ));
        $user = Auth::user();
        $campaign = new Campaign;

        $campaign->campaignName = $request->campaignName;
        $campaign->campaignDescription = $request->campaignDescription;
        $campaign->startDate = $request->startDate;
        $campaign->endDate = $request->endDate;
        $campaign->title = $request->title;
        $campaign->notificationText = $request->notificationText;
        $campaign->body = $request->body;
        $campaign->user_id = $request->user_id;


        $campaign->save();
        $campaign->places()->sync($request->places, false);

    }
vipin93's avatar

$campaign->user_id = Auth::user()->id;

aminbaig's avatar

Thanks vipin.....but my question is slightly different.

see this code:

$campaign->save();
$campaign->places()->sync($request->places, false);

After saving the campaign in its respective table, this creates a record in the the associative table with the right values for campaign_id and place_id, the only record it doesn't insert is the user_id.

So if i create a campaign which has id 10, and if I have two places with ids 4 and 5, it will create these two records:

campaign_id    Place_id    user_id
10              4
10              5

I don't know how to pass the current logged in users id as well into the associative table using the above code for

$campaign->save();
$campaign->places()->sync($request->places, false);

So I guess basically what I now only need is that when the sync is called, along with the campaign and place id, the logged in user id is also inserted in associative table :-(

aminbaig's avatar

Thanks vipin for your reply. A bit confused about placing this code, should this be in the campaign model or place model?

aminbaig's avatar

I changed the code in the campaign model but i get this error:

QueryException in C:\xampp\htdocs\pompbazar\vendor\laravel\framework\src\Illuminate\Database\Connection.php line 770: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'pompbazar.app\user' doesn't exist (SQL: select `user_id` from `App\User` where `place_id` = 4)

This is how my code looks like now for the campaign model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Campaign extends Model
{
    protected $fillable=['user_id','campaignName','campaignDescription','startDate','endDate','title','notificationText','body'];

    public function places()
    {
        return $this->belongsToMany('App\Place', 'App\User', 'place_id', 'user_id');

        //return $this->belongsToMany('App\Place','App\User','Place_id', 'user_id');
    }
}
paulredmond's avatar

@aminbaig I suggest you read carefully through the has and belongs to many info in the docs - https://laravel.com/docs/5.3/eloquent-relationships

What you are getting is a SQL error, the second argument is the name of the pivot table in the database. The convention for the table name is to join the two model names in alphabetical order, so the convention would be campaign_place if you did this:

return $this->belongsToMany('App\Place');

You can override the pivot table name like this:

// In Campaign Model...
return $this->belongsToMany('App\Place', 'my_custom_table_name');

// In Place Model...
return $this->belongsToMany('App\Campaign', 'my_custom_table_name');

Also, I noticed this in your original question that you should never do:

$campaign->user_id = $request->user_id;

Never trust browser-submitted data for setting the user id, it can be changed in the browser and users can then hijack others' records.

aminbaig's avatar

Hi Paul,

Thank you for your reply and yes you are right, I should not be placing the userid there. Just new to web development.

I tried your tip and explicitly defined the table name, its working but now I am getting the data in the wrong columns:

id  campaign_id place_id    user_id
1       Null            1       1
2       Null            1       2

This is what my campaign model looks like now after making the changes:

return $this->belongsToMany('App\Place', 'campaign_place', 'place_id', 'user_id');

Please advise. The progress that I have made is that I getting the user id in the pivot table but not in the right column and one other column (Campaign_id) is not getting its value (which it previously was getting).

aminbaig's avatar

I also noticed in several examples that 3 columns are being used, for example:

id  product_id  shop_id

whereas I am using 4 columns in the pivot table:

id  campaign_id place_id    user_id

since the association table is between place and campaign, should i create a forth field for user_is?

Please or to participate in this conversation.