laravel inserting into multiple tables
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Handling data across multiple tables in your Laravel application can be quite challenging. You may need to insert the same information from one table to another, ensuring that related entities are correctly linked. In this blog post, we will walk through a comprehensive approach to handle this scenario effectively using Laravel's powerful Eloquent ORM and eloquent relationships.
Modeling Your Database
First, let us consider the database structure:php
Table 1 (something):
- id (primary key)
- name
- url
Table 2 (something_users):
- id (primary key)
- id_something (foreign key to Table 1)
- email
- passwordModel Creation
Your models should be set up in a way that supports the required functionality. 1. Create 'Something' model:php
class Something extends Eloquent {
protected $table = 'something';
protected $fillable = ['name', 'email', 'password'];
public $errors;
public function User()
{
return $this->belongsTo('User', 'id', 'id_something');
}
}php
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'something_users';
protected $hidden = array('password', 'remember_token');
public function Something()
{
return $this->belongsTo('Something');
}
}Controller Setup
In your controller, we will handle the insertion process. We'll use Laravel's built-in validation and database interaction features: 1. Get input from a form or request:php
$input = Input::all();
// some additional validations and formatting...php
$this->db->fill($input);
$this->db->password = Hash::make(Input::get('password'));
$this->db->push();
$this->db->save();Inserting Data into Multiple Tables
Now, we can insert the data in both tables using the following SQL: 1. Insert data into 'something' table:sql
insert into `something` (`name`, `email`, `password`) values...sql
insert into `something_users` (`id_something`, `email`, `password`) values...