Skip to content
Luca Ubiali Web Developer

Build a Livewire App With Me! - Models and Migrations

September 13th, 2024
Continuous Learning

Episode - https://laracasts.com/series/lets-build-a-livewire-app/episodes/3


This episodes starts with models creation:

1php artisan make:model Podcast -mf

I usually forget about the handy parameters m and f to create migration and factory together with the model.

One of the migrations creates a foreign key:

1Schema::table('episodes', function (Blueprint $table) {
2 $table->id();
3 $table->foreignId('podcast_id')->constrained();
4});

This is another thing I forget, what does constrained() really does. Looking at Laravel docs, that’s the equivalent of:

1Schema::table('episodes', function (Blueprint $table) {
2 $table->id();
3 $table->unsignedBigInteger('podcast_id');
4 
5 $table->foreign('podcast_id')->references('id')->on('podcasts');
6});

foreignId() takes care of creating the unsigned big int, while constrained() creates the reference to the external table id.

When creating the models Josh uses the $guarded property like this:

1class Episode extends Model
2{
3 protected $guarded = ['id'];
4}

This is the first time I see this way of handling mass assignment. Usually it’s either leave $guarded empty or set $fillable fields one by one. This seem a middle way between the two.