TALL Tales

Building a Site with Filament: Part 2 - Adding the Blog Models

27 Oct, 2022

One thing that isn't immediately clear with Filament is that you have to create your own Models before you start using the Filament Resources.

So, firstly we have to create our three Models that we will use for the Blog Posts. These will be Category, Tag and Post.

php artisan make:model Category -mc

The -mc add the end tells Laravel to also create a Migration and a Controller as well as the Model. We need to run this code for all 3 Models.

Next, we have to edit the Migrations so we have the correct fields in our database. I'm keeping it simple and the Category and Tag Migrations will be identical:

$table->id();

$table->string('name');
$table->string('slug')->unique();
$table->longText('description')->nullable();
$table->boolean('is_visible')->default(false);
$table->string('seo_title', 60)->nullable();
$table->string('seo_description', 160)->nullable();

$table->timestamps();

Posts will require something different:

$table->id();

$table->foreignId('user_id')->nullable()->cascadeOnDelete();
$table->string('title');
$table->string('slug')->unique();
$table->text('extract');
$table->longText('content');
$table->date('published_at')->nullable();
$table->string('seo_title', 60)->nullable();
$table->string('seo_description', 160)->nullable();
$table->string('image')->nullable();
$table->boolean('is_visible')->default(false);

$table->timestamps();

You'll notice that I haven't added any foreign keys for the Tags or Categories on the Post table. This is because they will all have Many-to-Many relationships.

So, we also need to create two 'pivot' tables. One for category_post and one for post_tag. These will be very simple with just the ids in each:

$table->id();

$table->foreignId('category_id')->constrained();
$table->foreignId('post_id')->constrained();
            
$table->timestamps();

Now we need to Migrate these tables:

php artisan migrate

Now that they are all created we need to add the Relationships to the Models and also set which fields we want Fillable or Guarded. We'll do that in the next post.