Level-5; Sheikh Hasina Software Technology Park, Jessore, Bangladesh

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) {





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();





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());

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 *