Ask me anything
Ithy Logo
Sign in to save

Creating a Simple Blog in Laravel 12

A comprehensive, step-by-step guide to set up your blog from scratch

rustic desk with laptop and coffee

Highlights

  • Initial Setup: Installation, project creation, and environment configuration
  • Database & Models: Setting up migrations, creating models, and defining the schema
  • CRUD & Views: Building controllers, routes, and blade views for full CRUD operations

Introduction

Laravel is one of the most popular PHP frameworks for building modern web applications, featuring elegant syntax and a robust toolset. Given its clear documentation and rich ecosystem, Laravel 12 enables developers to set up a complete, fully functional blog with relative ease. In this guide, we will walk through every step required to create a simple blog, ensuring that you understand both the underlying process and the best practices involved in using Laravel effectively.

The steps outlined here are designed for users who have a basic understanding of PHP and web development. By following these instructions, you will create a blog application capable of displaying posts, handling form submissions, and managing posts with full Create, Read, Update, and Delete (CRUD) functionalities. Let’s dive in and cover everything from setting up your project to running your Laravel application.


Step 1: Setting Up Your Laravel Project

Install Laravel

Before getting started, ensure that Composer is installed on your system, as it is the primary dependency manager for PHP. With Composer ready, open your terminal or command prompt and run the following command to create a new Laravel project named "blog":


# Create a new Laravel project using Composer
composer create-project laravel/laravel blog
  

If you have the Laravel installer installed globally, you can alternatively run:


# Using the Laravel Installer for a faster process
laravel new blog
  

Navigate into Your Project Directory

Once the project creation process completes, navigate into your newly created directory by running:


cd blog
  

This folder will contain all the Laravel framework code and your application-specific files.

Launch the Built-in Development Server

Laravel comes with its own development server, which is perfect for testing your application locally. You can start the server by using the following command:


php artisan serve
  

Once the server is running, open your web browser and navigate to the local address provided in the terminal, typically http://127.0.0.1:8000, to view the default Laravel welcome page.


Step 2: Environment Configuration and Database Setup

Configure Your Environment

The Laravel project utilizes a file named .env to handle environment-specific configurations such as database connection details. Open the .env file at the root of your project and set up your database connection parameters. For example:


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=your_username
DB_PASSWORD=your_password
  

Make sure to create a corresponding database named "blog" in your MySQL or preferred database management system.

Generate an Application Key

Laravel’s encryption services require an application key, which can be automatically generated by running:


php artisan key:generate
  

This command will update the APP_KEY variable in your .env file.


Step 3: Creating the Blog’s Data Structure

Database Migrations for Posts

Migrations allow you to programmatically define your database schema. Laravel 12 uses migrations to create tables and manage changes over time. To create a migration for the posts table, run the following command:


php artisan make:migration create_posts_table --create=posts
  

After creating the migration file in the database/migrations directory, open the file and define the schema for your posts table. Here is an example schema:


public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}
  

Now, execute the migration to create the table in your database:


php artisan migrate
  

Creating the Post Model

The Post model represents the blog posts in your application. To generate the model, run the following command:


php artisan make:model Post
  

This command creates a Post.php file in the app/Models directory. The model will be used to interact with the posts table and perform database operations through Laravel’s Eloquent ORM.


Step 4: Building the Blog Functionality with Controllers and Routes

Creating the Post Controller

Controllers are responsible for handling HTTP requests. Generate a controller named "PostController" by executing:


php artisan make:controller PostController
  

Open the newly created PostController.php file in the app/Http/Controllers directory. You will now implement methods that provide the CRUD functionality. Here’s an outline of critical methods:

Controller Methods Overview

Index Method: Fetches and displays all blog posts.
Create Method: Returns a view to create a new blog post.
Store Method: Validates and saves new posts to the database.
Show Method: Displays a single blog post in detail.

Here is a sample snippet to include in your controller:


public function index() {
    $posts = Post::all();
    return view('posts.index', compact('posts'));
}

public function create() {
    return view('posts.create');
}

public function store(Request $request) {
    $request->validate([
        'title' => 'required',
        'content' => 'required',
    ]);
    Post::create($request->all());
    return redirect('/');
}

public function show(Post $post) {
    return view('posts.show', compact('post'));
}
  

Defining Routes for the Blog Application

Routes map HTTP requests to controller methods. Open the routes/web.php file and define the following routes:


use App\Http\Controllers\PostController;

Route::get('/', [PostController::class, 'index']);
Route::get('/posts/create', [PostController::class, 'create']);
Route::post('/posts', [PostController::class, 'store']);
Route::get('/posts/{post}', [PostController::class, 'show']);
  

These routes ensure that users can view all posts, create a new post, store post data, and view a single post.


Step 5: Creating Blade Views for the Blog

Setting Up the View Structure

Laravel uses Blade as its templating engine. Create a folder named posts inside the resources/views directory. Within this folder, you will create several Blade files to handle displaying and creating posts.

Index View (index.blade.php)

The index view lists all blog posts. Create a file named index.blade.php with content similar to:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blog Posts</title>
</head>
<body>
    <h1>Blog Posts</h1>
    <a href="/posts/create">Create a New Post</a>
    <hr>
    <?php foreach($posts as $post): ?>
        <h2><a href="/posts/<?= $post->id ?>"><?= $post->title ?></a></h2>
    <?php endforeach; ?>
</body>
</html>
  

Create View (create.blade.php)

The create view displays a form for adding new blog posts. Create the file create.blade.php with the following sample content:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Post</title>
</head>
<body>
    <h1>Add New Post</h1>
    <form action="/posts" method="POST">
        <!-- CSRF token is essential for security -->
        <input type="hidden" name="_token" value="<?= csrf_token() ?>">
        <label for="title">Title:</label>
        <input type="text" id="title" name="title" required>
        <br>
        <label for="content">Content:</label>
        <textarea id="content" name="content" required></textarea>
        <br>
        <button type="submit">Submit</button>
    </form>
</body>
</html>
  

Show View (show.blade.php)

The show view is used to display the detailed content of a specific post. Create the file show.blade.php with sample content as follows:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Post</title>
</head>
<body>
    <h1><?= $post->title ?></h1>
    <p><?= $post->content ?></p>
    <a href="/">Back to Home</a>
</body>
</html>
  

Step 6: Testing and Running Your Blog

Start the Local Development Server

After setting up your controllers, routes, and views, run the local development server if it is not already running:


php artisan serve
  

By visiting the URL provided in your terminal (normally http://127.0.0.1:8000), you should see the default page. To view your blog posts, navigate to the appropriate route (e.g., / for all posts, or /posts/create to add a new post).

Enhancing Your Blog Application

While this guide covers the fundamental steps for creating a simple blog, several enhancements can further improve your application:

  • User Authentication: Integrate Laravel’s authentication systems such as Laravel Breeze to allow user login and manage post authorship.
  • Image Uploads: Consider adding support for image uploads by modifying your migration and controller logic, and updating your forms to include file uploads.
  • Advanced Routing: Utilize route groups and middleware to manage access, performance, and scalability.

These improvements transform your basic blog into a more robust and secure web application.


Summary Table: Commands and Their Purposes

Command Purpose
composer create-project laravel/laravel blog Create a new Laravel project
cd blog Navigate into project directory
php artisan key:generate Generate an application encryption key
php artisan make:migration create_posts_table --create=posts Create a migration for the posts table
php artisan migrate Run database migrations
php artisan make:model Post Create a Post model
php artisan make:controller PostController Create a controller for handling blog post logic
php artisan serve Start the built-in development server

Conclusion

In this guide, you have learned how to create a simple blog in Laravel 12 by setting up a new project, configuring your environment, establishing a database, and building out the necessary models, controllers, routes, and views to implement complete CRUD functionality. Each step has been crafted to build your understanding of Laravel’s core components—from using migrations for database schema management to creating Blade templates for dynamic content display.

By following these step-by-step instructions, you now have a robust foundation on which to expand your application. Here are some final thoughts:

  • The modular structure of Laravel ensures that each component, such as routes, controllers, models, and views, works seamlessly together.
  • As you progress beyond this basic setup, consider implementing more advanced features like user authentication, authorization, image management, and API integrations.
  • Laravel’s vibrant community and extensive documentation provide continuous support and rich resources as you build more complex applications.

This guide not only serves as an introduction to Laravel’s powerful framework capabilities but also lays the groundwork for more advanced topics and implementations. Whether you are building your first blog or looking to integrate additional functionalities, mastering these basics is an essential step in your web development journey.


References


Recommended

laravel-news.com
Laravel News Blog

Last updated February 27, 2025

AI-assisted research. Sources, methodology and corrections · Source-checked guides and tools · Explore published answers

Ask Ithy AI