Rajat Hans Rajat Hans - 1 year ago 54
PHP Question

How to insert data into a pivot table with columns belonging to same model in Laravel?

I have a Block model which is basically for blocked users. It has a

and a
, both of which are IDs from the users table. How can I add data to this pivot table when a user wants to block another user? What should my relationship methods look like?

Answer Source

Since both target_id and sender_id are fields from the users table, your relationship must be defined this way.

class User {

  public function blocks() {
    return $this->belongsToMany('App\User','blocked_users','sender_id','target_id')->withPivot(['id']);

  public function blockedBy() {
    return $this->belongsToMany('App\User','blocked_users','target_id','sender_id')->withPivot(['id']);


Here blocked_users is the name of the table.

So, to block a user you can do :-

//User who is going to block
$user = User::find($id);
$inputs = [$target_user_id];

//or you can use,
$user->blocks()->sync($inputs, false);

The false in the above sync is used when the old synced rows are ignored and new ones are attached.

To get the list of users who that particular user has blocked, you can do :-

$user = User::find($id);

And to get the list of users who that particular user is blocked by

$user = User::find($id);