Laravel Eloquent: Saving two foreign keys at once

Necessary to store multiple foreign keys in single database transaction to minimize database call and queries. Associate function is very important to minimize possibilities of database transactions, and security issue of database transaction.
Lets assume you have a table with multiple foreign keys for example,
Schema::create('deliveries', function (Blueprint $table) { $table->increments('id'); $table->integer('client_id')->unsigned()->index(); $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade'); $table->integer('owner_id')->unsigned()->index(); $table->foreign('owner_id')->references('id')->on('owners')->onDelete('cascade'); $table->timestamp('delivery_date'); $table->timestamps(); });
In that case assume that your Delivery model is look like,
public function client() { return $this->belongsTo(Client::class); } public function owner() { return $this->belongsTo(Owner::class); }
Now you can use associate() function to save multiple foreign keys at once,
$delivery = new Delivery(); $delivery->client()->associate(Client::find($request->client_id)); $delivery->owner()->associate(Owner::find($request->owner_id)); $delivery->delivery_date=$request->delivery_date; $delivery->save();
If you want to minimize code in controller that you can use chaining in model
public function withOwner($user) {
$this->user()->associate($user); return $this;
}
public function withClient($client) {
$this->client()->associate($client); return $this;
}
Now your controller will be look neat then before,
$delivery = new Delivery($request->all()); $delivery->withClient($client)->withOwner($owner)->save()
Beautiful Laravel.
3 Responses
nice article about associate method !!
Thank you
Thanks man! Really helpfull