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
Considering your tables are users, signatures and user_signatures
Define the relation in model: User.php
Define the inverse of the relation in model: Signature.php
In your controller you could do the following:
The opposite is possible too:
Alternatively if you have an existing signature you should do:
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