3. Creating a Post Model, Controller and Migration
I started my SooperBlog application by creating a Post model, as well as a controller and a migration. All three of these files are quickly generated by running the following command:
php artisan make:model Post -mc
The make:model command generates a Post model, stored in the app/Models directory. The -mc flag generates a migration and a controller, located in the database/migrations and app/Http/Controllers directories respectively.
At this point, I can begin adding code to each of these files. I find it easiest to start with the migration setup. I know that I want a post to comprise of a heading, a subheading and some body text, so I can add these table columns to the migration and keep the default columns (the id and timestamps). I also know that each post should belong to a certain user and so I need to reflect this with a foreign key relationship. Below is my posts table migration, with the heading, subheading and body columns, as well as the foreign key relationship, where user_id relates to the id primary key in the users table.
We can see in the above migration that when a user is deleted, this cascades into the posts table, deleting any posts linked to the deleted user.
Comments
Post a Comment