Step 1: Create a Post
Model and Migration
First, generate a model and migration for the posts.
This will create two files:
-
Post model in
app/Models/Post.php
-
Migration file in
database/migrations/xxxx_xx_xx_create_posts_table.php
Migration: Define the posts
table
Open the migration file database/migrations/xxxx_xx_xx_create_posts_table.php
and modify it as follows:
Run the migration to create the posts
table:
Step 2: Define the Post
Model
Next, update the Post
model to include the relationships and fillable fields.
Step 3: Create the Post Controller
Now, create a controller to handle the logic for CRUD operations related to posts.
This will create a controller in app/Http/Controllers/PostController.php
. Open it and add the following code:
Step 4: Define Routes for Posts
Next, define the routes for handling the post actions. In routes/web.php
, add the following:
This single resource
route declaration will handle all necessary routes for the posts, such as:
-
GET /posts
- List posts (index) -
GET /posts/create
- Show form to create a post -
POST /posts
- Store a new post -
GET /posts/{post}/edit
- Show form to edit a post -
PUT /posts/{post}
- Update a post -
DELETE /posts/{post}
- Delete a post
Step 5: Create Views for Posts
Now, create the views to display and manage posts. These files will be located in resources/views/posts/
.
resources/views/posts/index.blade.php
This view will list all posts.
resources/views/posts/create.blade.php
This view will show the form to create a new post.
resources/views/posts/edit.blade.php
This view will show the form to edit an existing post.
Step 6: Run the Application
After creating these routes and views, you can now run the Laravel development server.
Navigate to http://localhost:8000/posts
in your browser. You should be able to:
-
View a list of posts.
-
Create new posts.
-
Edit and delete posts.
This gives you a complete Laravel blog post system with CRUD functionality. You can further improve this by adding features like authentication, image uploads, categories, or tags. If you need further assistance with any of these features, feel free to ask!