Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : Saving a belongsToMany relationship

Tags:

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

like image 910
Yobogs Avatar asked Jun 08 '15 08:06

Yobogs


People also ask

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.


2 Answers

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

like image 78
fahad.hasan Avatar answered Nov 03 '22 00:11

fahad.hasan


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 } 
like image 24
Saiyan Prince Avatar answered Nov 02 '22 22:11

Saiyan Prince