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.


3 Responses

  1. emu says:

    nice article about associate method !!

  2. Marcelo Dênis says:

    Thanks man! Really helpfull

Leave a Reply to emu Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.