Level-5; Sheikh Hasina Software Technology Park, Jessore, Bangladesh
+8801976062011
shahanur.sharif84

Laravel Eloquent: Saving two foreign keys at once

Read all about software development and Coding

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.

Creator of Shapecss, full stack developer and founder of MicroDreamIT. I wish to feel good if my blog help you developing your coding and career. I am also looking for project and consultancy. Please keep in touch with me in my twitter, facebook or other social network.

 

2 Responses

  1. emu says:

    nice article about associate method !!

Leave a Reply

Your email address will not be published. Required fields are marked *