Build a Blog with Laravel: A Complete Step-by-Step Guide

build blog with laravel

Building a blog can be an exciting way to share your thoughts, showcase your skills, or even start an online business. Just like you have a wide variety of blog types to choose from, you have many platforms available to build your blog.

While there are numerous options, Laravel offers a powerful and flexible way to create a fully customizable blog from scratch.

If you’re new to Laravel, don’t worry! This blog will guide you on how to build a blog with Laravel. By the end, you’ll have a complete blog. And if you ever need professional assistance for advanced features, you can always reach out to a Laravel development company to take it further. Let’s dive in and start building!

Prerequisites

Before we get started with Laravel blog development, ensure you have the following things in place:

If you are using any web server other than XAMPP, ensure it runs Apache or other software and that you have installed MariaDB on your local machine.

Building a Blog in Laravel

Once you are done with the prerequisites, gear up to create your blog with Laravel. Let’s start by creating a new project first.

Step 1: Create a New Laravel Project

The first step in building your blog with Laravel is to create a new project. For this guide, we’ll assume you’re using Windows.

  • Open your terminal or command line interface (CLI).
  • To create your Laravel project, run the following command:
laravel new blog
  • Once the project is created, navigate into the project’s directory:
cd blog
  • Open the directory in your code editor.
  • To make sure the project was created successfully, run the following:
php artisan serve
How to Build a Blog With Laravel

Click on the local address provided in the terminal to open your new Laravel project in the browser. You should see the default Laravel “Welcome” page, which means everything is set up correctly.

Step 2: Configure the Database

Now that the project is created, it’s time to configure the database.

php my admin
  • Open phpMyAdmin in your browser.
  • Under the Databases tab, create a new database by typing blog in the Create Database field and clicking Create.
  • Next, update your Laravel project to connect to this database:
  • In the root of your project, open the .env file.
  • Update the DB_DATABASE and DB_PASSWORD fields with the name and password you created:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=your-db-username
DB_PASSWORD=your-db-password

Make sure to save the .env file once you’ve made these changes.

Step 3: Create the Posts Table

Now, let’s create a table to store your blog posts.

In the terminal, run the following command to create a new model, migration, and controller for your posts:

php artisan make:model Post -mc
  • This command will create a Post model, a posts table, and a migration file.
  • Navigate to the database/migrations directory and find the migration file to create the posts table. It will have this format: YYYY_MM_DD_create_posts_table.php.
  • Inside the up() method of this migration file, define the schema for the posts table. For example, you might add fields for title, description, and image:
public function up() {
  Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title')->nullable();
    $table->text('description')->nullable();
    $table->string('image')->nullable();
    $table->timestamps();
  });
}
  • After defining the schema, run the migration to create the table in your database:
php artisan migrate
  • Head over to phpMyAdmin and check your database. You should now see a posts table with the columns you just defined.

Step 4: Create Controllers and Views

With your database set up and the posts table ready, it’s time to implement the business logic and create the views for your blog.

Install Dependencies

Before we begin creating controllers and views, let’s install the necessary frontend dependencies. In your terminal, run the following commands:

npm install
npm run dev

The first command installs the necessary Node.js packages, while the second command starts a Vite development server to bundle your assets.

Create a Post Controller

Laravel controllers manage the flow of data between your models and views. To create a controller for your blog posts:

  • Run the following command to generate a new controller called PostController:
php artisan make:controller PostController

Open the newly created PostController.php file located in the app/Http/Controllers directory.

Add the following method to render a sample blog post:

public function index() {
    $post = "Laravel Blog Post Example!";
    return view('posts.index', ['post' => $post]);
}

This method defines a simple $post variable that contains text. It passes this data to a view named posts.index.

Set Up Blade Layouts

Laravel uses Blade, its powerful templating engine, to manage views. Blade allows you to create reusable layouts and components, simplifying your development process.

  • Navigate to the resources/views directory and create two new directories: layouts and posts.
  • Inside the layouts folder, create a file named app.blade.php. This will serve as the base layout for all views. Add the following HTML structure:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Blog</title>
    <!-- Styles -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
    <!-- Navbar -->
    <header>
        <nav class="navbar bg-primary">
            <div class="container-fluid">
                <a class="navbar-brand" href="{{ route('posts.index') }}">Laravel Blog</a>
            </div>
        </nav>
    </header>

    <!-- Content -->
    @yield('content')

    <!-- Footer -->
    <footer class="footer mt-auto py-3 bg-dark">
        <div class="container d-lg-flex justify-content-between">
            <span class="text-light">Laravel Blog (c) 2023</span>
        </div>
    </footer>
</body>
</html>

This layout includes a header with a navigation bar and a footer. The @yield(‘content’) directive is where child views will insert their content.

Create the Blog Post View

Next, we need to create a view to display the blog post content.

Inside the posts directory (which you created earlier), create a new file called index.blade.php.

Add the following code to this file:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="titlebar">
        <h1>Blog Post</h1>
    </div>
    <hr>
    <p>{{ $post }}</p>
</div>
@endsection

This view extends the app.blade.php layout and displays the $post variable passed from the controller.

Define Routes

To make everything functional, you need to define the necessary routes.

  • Open the routes/web.php file.
  • Add the following line to define the route for the PostController:
use App\Http\Controllers\PostController;
Route::resource('posts', PostController::class);

This will register the necessary routes to handle your blog posts.

Now, with the Vite server running, you can start Laravel’s built-in server by running:

php artisan serve

Open your browser and go to http://127.0.0.1:8000/posts to view the blog post.

Step 5: Create the Blog Post Page

Now, let’s add the ability to create and store blog posts.

Update the Post Model

First, you need to tell Laravel which fields in the posts table are fillable, meaning they can be mass-assigned when creating or updating a post.

In the app/Models/Post.php file, update the class to include the fillable attributes:

protected $fillable = ['title', 'description', 'image'];

This ensures that only the specified fields can be mass-assigned, providing a layer of security.

Create Controller Methods for Posts

Next, let’s update the PostController to display all posts and allow users to create new ones.

Open the PostController.php file.

Add the following methods for displaying all posts and showing the form to create a new post:

// Show all posts
public function index() {
    $posts = Post::orderBy('created_at', 'desc')->get();
    return view('posts.index', ['posts' => $posts]);
}

// Show form to create a post
public function create() {
    return view('posts.create');
}

The index method fetches all posts from the database and orders them by creation date, while the create method returns a view where users can create a new post.

Create the Store Method to Save Posts

Next, add a method to store new posts in the database.

Add the following store method in the PostController:

// Store a new post
public function store(Request $request) {
    // Validate the input
    $request->validate([
        'title' => 'required',
        'description' => 'required',
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    // Handle image upload
    $file_name = time() . '.' . request()->image->getClientOriginalExtension();
    request()->image->move(public_path('images'), $file_name);

    // Create and save the new post
    $post = new Post;
    $post->title = $request->title;
    $post->description = $request->description;
    $post->image = $file_name;
    $post->save();

    // Redirect to the posts index page with a success message
    return redirect()->route('posts.index')->with('success', 'Post created successfully.');
}
  • Validation: Ensures that the title, description, and image fields are required. The image field is also validated to accept only image files (JPEG, PNG, etc.).
  • File Upload: The uploaded image is saved in the public/images folder, and its filename is generated using the current timestamp.
  • Database Save: A new Post object is created, populated with the requested data, and saved to the database.

Now, when a user submits a new post, it will be saved to the database, and they will be redirected to the posts list with a success message.

Step 6: Add Routes to Your Posts

The next step is to register routes for your post-related controller methods. This will allow Laravel to automatically handle the creation, storage, and display of posts.

  • Open the web.php file in the routes directory at the root of your project.
  • Replace the existing code in web.php with the following:
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::resource('/', PostController::class)->names([
    'index' => 'posts.index',
    'create' => 'posts.create',
    'store' => 'posts.store',
    'show' => 'posts.show',
]);

This code registers the routes for all the methods in PostController:

  • index: Displays a list of posts.
  • create: Shows the form to add a new post.
  • store: Saves a new post to the database.
  • show: Displays a specific post.

Step 7: Make Blade Files

Now that the routes are set, you need to create the views (Blade files) to display posts and the form to create new posts.

Create the create.blade.php File

  • In the resources/views/posts directory, create a new Blade file – create.blade.php.
  • Add the following code to the file:
@extends('layouts.app')

@section('content')
<div class="container">
    <h1>Add Post</h1>
    <section class="mt-3">
        <form method="post" action="{{ route('posts.store') }}" enctype="multipart/form-data">
            @csrf

            <!-- Error messages when data is invalid -->
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            <div class="card p-3">
                <label for="floatingInput">Title</label>
                <input class="form-control" type="text" name="title">

                <label for="floatingTextArea">Description</label>
                <textarea class="form-control" name="description" id="floatingTextarea" cols="30" rows="10"></textarea>

                <label for="formFile" class="form-label">Add Image</label>
                <input class="form-control" type="file" name="image">
            </div>

            <button class="btn btn-secondary m-3">Save</button>
        </form>
    </section>
</div>
@endsection

Here’s a breakdown of what this code does:

  • @extends(‘layouts.app’) tells Blade to extend the layout defined in app.blade.php.
  • The form uses the POST method with the {{ route(‘posts.store’) }} action to store the post. The enctype=”multipart/form-data” allows for image uploads.
  • @csrf protects the form from cross-site request forgery.
  • If any validation errors occur (like missing fields), they are displayed in the form.

Update the File

  • Next, we’ll update the view to display all blog posts.
  • In the resources/views/posts directory, open the index.blade.php file.
  • Replace the existing code with the following:
@extends('layouts.app')

@section('content')
<div class="container">
    <div class="titlebar">
        <a class="btn btn-secondary float-end mt-3" href="{{ route('posts.create') }}" role="button">Add Post</a>
        <h1>Mini post list</h1>
    </div>

    <hr>

    <!-- Success message if a post is created successfully -->
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif

    <!-- Display posts if they exist -->
    @if (count($posts) > 0)
        @foreach ($posts as $post)
            <div class="row">
                <div class="col-12">
                    <div class="row">
                        <div class="col-2">
                            <img class="img-fluid" style="max-width:50%;" src="{{ asset('images/'.$post->image)}}" alt="">
                        </div>
                        <div class="col-10">
                            <h4>{{ $post->title }}</h4>
                        </div>
                    </div>
                    <p>{{ $post->description }}</p>
                    <hr>
                </div>
            </div>
        @endforeach
    @else
        <p>No Posts found</p>
    @endif
</div>
@endsection

Here’s what this code does:

  • Add Post Button: The Add Post button links the form for creating new posts.
  • Success Message: Displays a success message when a post is created successfully.
  • Displaying Posts: The @foreach loop checks if there are any posts in the database. If there are, it iterates through them and displays the title, description, and image for each post. If no posts exist, it shows No Posts found.

Step 8: Test the Application

Now that everything is set up, let’s test the application.

Add a Post:

  • Navigate to http://127.0.0.1:8000/posts in your browser.
  • Click on the Add Post button, fill out the form with a title, description, and image, then submit it.

View Posts:

  • After adding the post, you should be redirected back to the post list.
  • The new post should be displayed with its title, description, and image.

Check Validation:

  • Try submitting the form without filling out all required fields. You should see error messages prompting you to fill them in.

Struggling with Laravel development?

How to Deploy Your Laravel Blog

Once you have tested your blog and are ready to make it live, it’s time for deployment. There are many application deployment services available in the market. Here, we will use Laravel Forge.

Step 1: Set Up Laravel Forge

Before we can deploy your Laravel app, we first need to create an account on Laravel Forge. This tool will allow us to automate the server setup and manage the infrastructure efficiently.

Create a Laravel Forge Account

  • Go to the Laravel Forge website and sign up for an account.
  • After signing in, you’ll land on the Forge dashboard.

Link a Cloud Provider

  • In the Forge dashboard, click on Create Server.
  • Choose a cloud provider from the options: DigitalOcean, Linode, AWS, Vultr, or Hetzner.
  • Connect your cloud provider by following the on-screen instructions.
  • Forge will now be able to create and manage servers on your behalf.

Step 2: Provision Your Server

Now that Laravel Forge is connected to your cloud provider, you can provision a new server where your blog will be hosted. This is where your Laravel application will live and serve content to your users.

Create a New Server

Click Create Server on the Forge dashboard.

Configure the server:

  • Provider: Choose the cloud provider you linked earlier (e.g., DigitalOcean).
  • Server Size: Select a server size appropriate for your blog (e.g., a 1GB RAM server is fine for small applications).
  • Region: Choose a region close to your target audience.
  • Database: By default, Forge will install MySQL, but you can select other options like PostgreSQL if needed.

Name your server (e.g., LaravelBlogServer).

Click Create Server. Forge will start provisioning the server, which can take a few minutes.

Set Up SSH Access

  • Once the server is created, Forge will set up SSH access for you.
  • You’ll see the server’s IP address and SSH credentials on the dashboard.
  • Forge will automatically install Nginx, PHP, MySQL (or other selected databases), and other dependencies necessary for Laravel.

Step 3: Configure Your Domain

After your server is provisioned, the next step is to point your domain to the server so users can access your Laravel blog via your domain name. This will allow visitors to reach your site from a custom URL.

Point Your Domain to Your Server

  • Go to your domain registrar and update your DNS settings.
  • Add an A record that points your domain (e.g., example.com) to the server’s IP address (which you got from Forge).
  • Wait for the DNS to propagate (this may take a few minutes to several hours).

Add Your Domain to Forge

  • In Forge, go to the Sites section of your newly provisioned server.
  • Click Add Site.
  • Enter your domain name (e.g., example.com) and click Create Site.
  • Forge will automatically configure Nginx to point to your Laravel application and handle the routing for that domain.

Step 4: Deploy Your Laravel Blog

With your domain configured, it’s time to deploy your Laravel blog by connecting Forge to your Git repository and pulling the latest code. This will allow Forge to automatically manage deployments every time you push changes.

Push Your Code to Git

  • Before deploying, ensure your Laravel blog’s code is stored in a Git repository (GitHub, GitLab, Bitbucket, etc.).
  • Initialize a Git repository in your project folder if you haven’t done so already:
git init
git add .
git commit -m "Initial commit"
git remote add origin <your-git-repo-url>
git push -u origin master

Connect Git to Laravel Forge

In the Source Control section of Forge, connect your Git account (GitHub, GitLab, or Bitbucket).

Once connected, select the repository that contains your Laravel blog project.

Forge will automatically pull the code from your Git repository during deployment.

Step 5: Configure Environment Variables

To ensure your application works properly in a production environment, you’ll need to update your environment variables. These settings, stored in your .env file, include information about your database, app name, and more.

Update the .env File

  • After deploying your code, go to the Environment tab for your site in Forge.
  • Update the .env file with your specific configuration. Some key values to set are:
APP_NAME=LaravelBlog
APP_ENV=production
APP_KEY=your-app-key
APP_URL=https://example.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password
  • Make sure APP_ENV is set to production for a live site.

Step 6: Set Up the Database

With your environment variables configured, it’s time to create a database and connect it to your Laravel blog. This will allow you to store your blog posts and other data.

Create a New Database

  • In Forge, go to the Database section for your server.
  • Click Create a New Database, and provide the following:
  • Database Name (e.g., laravel_blog).
  • Username and Password for accessing the database.

Update Database Credentials in .env

  • Go back to the Environment tab and update the database credentials in your .env file to match the newly created database:
DB_DATABASE=laravel_blog
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password
Run Database Migrations
  • Open an SSH connection to your server, or use Forge’s terminal.
  • Run your database migrations:
php artisan migrate --force

The –force flag is necessary in production to ensure the migrations execute.

Step 7: Set Up SSL for Security

To secure your site and enable HTTPS, you should set up SSL. Laravel Forge makes it easy to configure SSL certificates using Let’s Encrypt.

Install SSL Certificate

  • In the SSL section of Forge, click Let’s Encrypt to automatically generate and install a free SSL certificate for your domain.
  • This secures your website and enables HTTPS.

Force HTTPS

  • In the Nginx section of Forge, enable the option to Redirect HTTP to HTTPS to ensure that all traffic is securely encrypted.

Step 8: Configure Deployment Scripts

Deployment scripts ensure that every time you push changes to your code repository, Forge automatically installs the latest dependencies, migrates the database, and performs other necessary tasks.

Set Up Your Deployment Script

  • In the Deployment section of Forge, click on Deployment Script.
  • Replace the existing script with the following:
# Pull the latest changes from the Git repository
git pull origin master

# Install PHP dependencies
composer install --no-interaction --prefer-dist --optimize-autoloader

# Run database migrations
php artisan migrate --force

# Clear and cache configuration, routes, and views
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Restart PHP to apply changes
sudo service php8.1-fpm reload

This script ensures that your application is up to date with the latest code and that necessary optimizations are applied.

Deploy the Application

  • Once your deployment script is set, click Deploy Now to trigger the deployment process.
  • Forge will pull the latest code from your Git repository, install dependencies, and run the necessary commands to make the site live.

FAQs on Building a Blog with Laravel

Is Laravel good for blogging?
Yes, Laravel is great for building blogs. It’s known for its speed, flexibility, and security. With Laravel, you can quickly set up a blog and scale it as your traffic grows while enjoying features like clean code structure and robust performance.
How do I get people to read my blog?
To get more readers, focus on creating high-quality, engaging content. Promote your blog on social media, optimize it for search engines (SEO), and interact with your audience. You can also offer incentives, like free downloads, to encourage visitors to subscribe.
What are the key features of a blog?
A good blog includes easy navigation, a search function, an archive section, comment support, and share buttons for social media. These features make it easy for readers to explore content and engage with your posts.

Start Your Blogging Journey Today!

Building a blog with Laravel is a smart choice if you’re looking for a flexible and powerful platform. Its speed, security, and scalability make it easy to get started and grow over time. Whether you’re a beginner or an experienced developer, Laravel’s features will help you create a blog that’s both functional and easy to manage.

Now that you know the basics, it’s time to start building your blog! If you need help with development or maintenance, hire Laravel developers for a perfect solution.

To create a secure and scalable blog.

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment