The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

12 Days of Eloquent

Published on by

12 Days of Eloquent image

Playing with laravel eloquent while singing a holiday song.

Let's start by cloning the repo I've got setup for us.

git clone https://github.com/ronnorthrip/twelvedays.git

Then cd into the project; install it; copy the env file; run the default migrations.

cd twelvedays
composer install
cp .env.example .env
php artisan migrate
php artisan key:generate

OK, now we're ready to go! Our task today is to build a laravel command that will sing our little song.

php artisan make:command SingTwelveDays

Now open this file (its in app/Console/Commands) in your favorite text edit and change the signature at the top, the description, and the handle function to just info out a placeholder for now.

protected $signature = 'sing:twelvedays';
 
protected $description = 'Sing the Twelve Days of Eloquent';
 
public function handle()
{
$this->info('The Twelve Days of Eloquent');
}

Lets try it out.

php artisan sing:twelvedays

Sweet!

OK, how does this song go?

One the first day of Eloquent
My framework gave to me
A partridge in a pare tree

So how are we going to build this?

We have a Partridge, and we have a Pare Tree, so we can abstract those as an Animal and a Location, and the animal (the partridge) has a location (the pare tree). This exactly what eloquent's one to one relationships are meant to represent. And we'd have to pick which model belongs to which or if we wanted to have multiple.

But if we look forward just a bit we realize that the lines are not consistent. In fact the only thing that's actually in anything is that first line! Even more, the fourth "calling birds" doesn't match the order of the latter lines where the activity is at the end of the sentence!!

A partridge in a pear tree!
Two turtle doves,
Three French hens,
Four calling birds,
Five golden rings,
Six geese a-laying,
Seven swans a-swimming,
Eight maids a-milking,
Nine ladies dancing,
Ten lords a-leaping,
Eleven pipers piping,
Twelve drummers drumming,

So if we break down each word into a singable bite of the song we can break out the big daddy of eloquent, the many to many polymorhpic relationship. We will call these pieces 'singable'.

So for this kind of relationship each of the things we care about (Activity, Animal, Country, Location, Person) we store it's id and type so that we have a unique reference back to them. So lets add the singables table too our migrations.

Open the migrations file called '2025_12_19_000000_create_the_tables.php' and we'll add a 'singables' table to the end of the up function.

Schema::create('singables', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('day_id');
$table->string('singable_type');
$table->unsignedBigInteger('singable_id');
$table->timestamps();
});

Now that lets build a fresh database with migrate:fresh.

php artisan migrate:fresh

So now start working on the line again.

A partridge in a pare tree

Since it's an Animal we will open that model and add a MorphToMany relationship.

public function singable(): MorphToMany
{
return $this->morphToMany(Singable::class, 'singable');
}

We also need to add the inverse definition in Singable model, so open it and add a MorphTo relationship.

public function singable(): MorphTo
{
return $this->morphTo();
}

As you can see the belongs to relationship back to the Day model is already in place.

Now we can test these in tinker

php artisan tinker
$day = \App\Models\Day::create(['name'=>'First']);
$animal = \App\Models\Animal::create(['name' => 'Partidge']);
$lyric = $day->lyrics()->make();
$lyric->singable()->associate($animal)->save();
$day->lyrics()->get();

You should see an eloquent collection with a singable model attached with type "App\Models\Animal".

Tinker is a great place to poke around your code and hack on things until you've figured out how to do your task. When you're done with tinker you can type 'exit' or Ctrl+C.

Now we will extract the singable function it to a trait that we can easily use across all our models. So first go back to your editor and switch bacak to the Animal model, then cut the singable function, and open the CanBeSung.php trait. And then paste the function into. Now we need to add that trait to the Animal model right after the current use line (use HasFactory).

use CanBeSung;

By the way, that trait has already been used on the other models already, so we should be able to make a location too!

Now after you've done your edit lets launch tinker again and make sure its working.

php artisan tinker
$day = \App\Models\Day::create(['name'=>'First']);
$animal = \App\Models\Animal::create(['name' => 'Partidge']);
$location = \App\Models\Location::create(['name' => 'Pear Tree']);
$lyric1 = $day->lyrics()->make();
$lyric2 = $day->lyrics()->make();
$lyric1->singable()->associate($animal)->save();
$lyric2->singable()->associate($location)->save();
$day->lyrics()->with('singable')->get();

"With" allows us to pull the related model's data over the relationship so we can have all of it available for us to use. This is very handy.

The last line here is the core of the solution singing a line using the relationships we've built. It gets all of the lyrics for the day with it's related singable thing. All we have to do is pluck out just the part we need ('singable.name') and add spaces between them.

So exit tinker and open the Day model and the line function to the bottom.

public function line(): string
{
return $this->lyrics()->with('singable')->get()->pluck('singable.name')->implode(' ');
}

Ok then back to tinker for one last test!

Since we saved stuff in the previous tinker session it should still be in the database.

php artisan tinker
$day = \App\Models\Day::latest()->first();
$day->line();

Did you get "Partidge Pear Tree"?

Excellent! Ok, exit tinker.

Now we're going to build a fresh copy of the database to get rid or any of our testing data and seed it with the song useful dev data.

php artisan migrate:fresh --seed

We've now come full circle to the actual singing command. Open (or swith to) SingTwelveDays.php in your text editor. Of course the handle method hasn't changed, it's just a placeholder.

The part we're trying to sing is

One the first day of Eloquent
My framework gave to me
A partridge in a pare tree

So for each of the days we need to use the name on the first line. And the second line is the same for each verse. And the line we calculated in the line function in the day model. So lets make these changes and try it out.

public function handle()
{
\App\Models\Day::all()->each(function ($day) {
$this->info("On the ".$day->name." day of Eloquent");
$this->info("My framework gave to me");
$this->info($day->line());
$this->info("");
sleep(2);
});
}
php artisan sing:twelvedays

Well how about that?

Wishing you the Happiest of Holidays, Laravel Friends
From Your Friendly Neighborhood White Beard

-Ron

Ron Northrip photo

Your friendly neighborhood white beard!
Organizer of the KYPHPUG meetup
Building Draftsman - a visual dev tool
dev, father, husband, friend, wine-drinker, foodie, musician

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Filament v5.2.0 Adds a Callout Component image

Filament v5.2.0 Adds a Callout Component

Read article
OpenAI Releases GPT-5.3-Codex, a New Codex Model for Agent-Style Development image

OpenAI Releases GPT-5.3-Codex, a New Codex Model for Agent-Style Development

Read article
Claude Opus 4.6 adds adaptive thinking, 128K output, compaction API, and more image

Claude Opus 4.6 adds adaptive thinking, 128K output, compaction API, and more

Read article
Laravel Announces Official AI SDK for Building AI-Powered Apps image

Laravel Announces Official AI SDK for Building AI-Powered Apps

Read article
`hasMany()` Collection Method in Laravel 12.50.0 image

`hasMany()` Collection Method in Laravel 12.50.0

Read article
Mask Sensitive Eloquent Attributes on Retrieval in Laravel image

Mask Sensitive Eloquent Attributes on Retrieval in Laravel

Read article