Laravel : Saving a belongsToMany relationship

59.8k views Asked by At

I want to save a new signature in my table signature. Each signature can be linked to multiples users. I have a many to many table between Users and Signatures.

My Model Signature is :

class Signature extends Model {
   public $fillable = ['name', 'template'];

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

My Controller SigantureController.php is :

public function store(CreateSignaturesRequest $request)
{
    //return $user_id;
    $values = $request->only(['name','template']);

    Signature::create($values));

    return response()->json(['message'=>'SUCCESS'], 201);

}

How can I do to Create my Signature and link it to a user ?

I tried

Signature::create($values)->associate($user_id);

Thanks

3

There are 3 answers

3
fahad.hasan On BEST ANSWER

Considering your tables are users, signatures and user_signatures

Define the relation in model: User.php

class User extends Model {
   public function signatures() {
       return $this->belongsToMany('\App\Signature', 'user_signatures');
   }
}

Define the inverse of the relation in model: Signature.php

class Signature extends Model {    
   public function users() {
       return $this->belongsToMany('\App\User', 'user_signatures');
   }
}

In your controller you could do the following:

//create a new signature
$signature = new Signature($values);
//save the new signature and attach it to the user
$user = User::find($id)->signatures()->save($signature);

The opposite is possible too:

$user = User::find($user_id);
$signature = Signature::create($values)->users()->save($user);

Alternatively if you have an existing signature you should do:

$user = User::find($id);
$user->signature()->attach($signature->id);

Please note that attach() and detach() accepts an id or an array of ids.

Laravel docs has covered this in much more details and better examples. You should check attach(), detach() and sync() methods. Please have a look: http://laravel.com/docs/5.0/eloquent#inserting-related-models

2
Saiyan Prince On

You need to have a table called user_signature with the following schema:

$table->integer('user_id')->unsigned();
$table->integer('signature_id')->unsigned();

$table->foreign('user_id')->references('id')->on('users');
$table->foreign('signature_id')->references('signatures')->on('users');

Then your User model should have the following method:

Model User

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

Now that you have developed the Many-To-Many relationship between the models what you can do is this:

While storing a new record (the controller you are using for the signature):

 /**
 * Insert the signature
 *
 * @param Request $request
 * @return ...
 */
 public function store( Request $request ) {
    // your validation

    $signature->users()->attach( $request->input('user_id') );

    // return
}

Similarly while updating the record (the controller you are using for signature):

/**
 * Update the signature with the particular id
 *
 * @param $id
 * @param Request $request
 * @return ...
 */
 public function update( $id, Request $request ) {
    // your validation

    $signature->users()->sync( $request->input('user_id') );

    // return
}
1
Yasen Zhelev On

First of all associate requires a model object to be passed as arguments. See here: http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Relations/BelongsTo.html#method_associate

Is is also for belongsTo relationships, not Many to Many as is in your case. See here: http://laravel.com/docs/5.0/eloquent#inserting-related-models

Based on that what you should do is:

Signature::create($values)->users()->attach($user_id);