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 twelvedayscomposer installcp .env.example .envphp artisan migratephp 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