How to create Eloquent model with relationship?
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Developing efficient applications often requires you to manage several entities, their relationships, and the data they contain. Laravel's Eloquent model is a powerful tool that provides an object-oriented interface for working with database tables. In this post, we will focus on creating Eloquent models with their corresponding relationship in a more beautiful and streamlined manner using Laravel.
Setting Up the Database Tables
Firstly, let's set up our two database tables: "Person" for storing person-related data (firstname and lastname) and "Employee" to store employee details (position). The database schema could look like this:sql
CREATE TABLE persons (
id SERIAL PRIMARY KEY,
firstname VARCHAR(255),
lastname VARCHAR(255)
);
CREATE TABLE employees (
id INT NOT NULL AUTO_INCREMENT,
person_id INT,
position VARCHAR(100),
FOREIGN KEY (person_id) REFERENCES persons(id)
);Creating the Models
Now let's create an "Employee" Eloquent model that inherits from Laravel's Model class and includes the necessary columns. The Person model can be created in a similar way:php
class Employee extends Model {
protected $fillable = ['firstname', 'lastname', 'position'];
// Define relationships with the Person model here, if needed
}Creating Eloquent Model with Relationship
To create an instance of the Employee model (including its related person) in a more beautiful way, we can utilize Eloquent relationships' 'create' method:php
use App\Person; // Import Person model here
use App\Employee; // Import Employee model here
// Create new employee and associate it with the created person instance:
$person = new Person();
$person->firstname = 'Jack';
$person->lastname = 'London';
$person->save(); // Save first person record
$employee = new Employee();
$employee->position = 'writer';
$employee->person_id = $person->id;
$employee->save(); // Save employee instance, linking with the person