How to Create a Blog with Laravel

Laravel is the most popular PHP framework. We all know people prefer this framework to build their web applications. And while building a website with Laravel, you probably want to build a blog on your website. In general, Laravel is not a blogging platform like WordPress where you get all the backend stuff ready to manage your blog articles. And building the blog system from scratch is quite time-consuming work. Thanks to Canvas which makes Laravel developers life easy by building a cool publishing platform for Laravel.

Using the Canvas package, we can easily build our blog in Laravel in just a few minutes. Canvas already did hard work for managing the blog’s backend stuff. You all need to do is just get the data and display it on the frontend matching your design.

Having said that, let’s take a look at how to create a blog with Laravel using the Canvas package.

Getting Started

In order to get started with Canvas, you need to first satisfy the basic requirement of Canvas which is user authentication. Laravel makes implementing authentication really simple. If you have already installed Laravel authentication then skip this step. Else in your terminal, run the below commands one by one to setup Laravel authentication.

composer require laravel/ui --dev
php artisan ui vue --auth
npm install && npm run dev

Create a blog with Laravel using Canvas Package

Once authentication is at the place you can install the Canvas by running the below command:

composer require cnvs/canvas

Upon package installation, you need to publish assets and primary configuration file. Publish it using the command:

php artisan canvas:install

This command would locate the primary configuration file at config/canvas.php. You can control various aspects using this configuration file. But you rarely need to touch this file as all stuff is already defined at the places.

It also creates a few tables in your database. This package adds a ‘canvas_’ prefix to all these newly created tables.

When it comes to blogs, you always need to use images in the content. So, create a symbolic link to ensure file uploads are publicly accessible from the web.

php artisan storage:link

It means you will see your uploaded images inside public/storage directory.

Now, if you run the URL http://localhost:8000/canvas you will redirect to the statistics page. You may redirect to the login page if you have not logged in. Here I use the localhost, you can adjust this URL.

On the statistics page, you will get basic analytics of your blog like the number of views, visitors, the trend of each article, etc.

From the header section, you can get the menus for creating posts, tags, topics, Settings, etc. You have to play with all these menus. It’s simple and easy to understand.

Blog Settings

On clicking on the ‘New Post’ button, you will redirect to a page where you can add your article. You can also add featured images, SEO settings, tags, topics to the article. Notice the three dots next to the Publish button. Clicking on these dots you get all these options.

Article Setting

Above screenshot showing background color as I set dark mode to on. In your case, you may see the white background. So don’t get confused with it. The user can find this dark mode feature on the Settings page.

Canvas has an auto-saving feature so that you will not lose your work.

The interface of this package is straight-forward. You can easily get familiar with it in no time. The next thing we need to see is displaying your articles on the front end.

Publishing Articles on Website

Once you are done with the backend, you need to display your articles on the front end. It requires defining a few routes and methods in the controller file. The Canvas library did this hard work for you. On the GitHub page of this library, you will get the code for it. Add the below routes in your routes/web.php file.

// Get all published posts
Route::get('blog', 'BlogController@getPosts');

// Get posts for a given tag
Route::get('tag/{slug}', 'BlogController@getPostsByTag');

// Get posts for a given topic
Route::get('topic/{slug}', 'BlogController@getPostsByTopic');

// Find a single post
Route::middleware('Canvas\Http\Middleware\Session')->get('{slug}', 'BlogController@findPostBySlug');

Create a controller BlogController using the command:

php artisan make:controller BlogController

Your BlogController.php will have the code below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BlogController extends Controller
{
    public function getPosts()
    {
        $data = [
            'posts' => \Canvas\Post::published()->orderByDesc('published_at')->simplePaginate(10),
        ];

        return view('blog.index', compact('data'));
    }

    public function getPostsByTag(string $slug)
    {
        if (\Canvas\Tag::where('slug', $slug)->first()) {
            $data = [
                'posts' => \Canvas\Post::whereHas('tags', function ($query) use ($slug) {
                    $query->where('slug', $slug);
                })->published()->orderByDesc('published_at')->simplePaginate(10),
            ];

            return view('blog.index', compact('data'));
        } else {
            abort(404);
        }
    }

    public function getPostsByTopic(string $slug)
    {
        if (\Canvas\Topic::where('slug', $slug)->first()) {
            $data = [
                'posts' => \Canvas\Post::whereHas('topic', function ($query) use ($slug) {
                    $query->where('slug', $slug);
                })->published()->orderByDesc('published_at')->simplePaginate(10),
            ];

            return view('blog.index', compact('data'));
        } else {
            abort(404);
        }
    }

    public function findPostBySlug(string $slug)
    {
        $posts = \Canvas\Post::with('tags', 'topic')->published()->get();
        $post = $posts->firstWhere('slug', $slug);

        if (optional($post)->published) {
            $data = [
                'author' => $post->user,
                'post'   => $post,
                'meta'   => $post->meta,
            ];

            // IMPORTANT: This event must be called for tracking visitor/view traffic
            event(new \Canvas\Events\PostViewed($post));

            return view('blog.show', compact('data'));
        } else {
            abort(404);
        }
    }
}

Create Blade Files

As defined in the controller, let’s create a blade file blog/index.blade.php and blog/show.blade.php. In this tutorial, I am not going to design a blog listing and detail page. As each one of you has a separate design. I am just going to print articles on the blade file. You can apply design matching with your website.

blog/index.blade.php

<ul>
    @foreach($data['posts'] as $d)
        <li>
            <h2><a href="{{url($d['slug'])}}">{{ $d['title'] }}</a></h2>
            <p>{!! $d['body'] !!}</p>
        </li>
    @endforeach
</ul>

blog/show.blade.php

@if($data['post']['featured_image'])
    <img src="{{ url($data['post']['featured_image']) }}" alt="{{ $data['post']['featured_image_caption'] }}" />
@endif
<h2>{{ $data['post']['title'] }}</h2>
{!! $data['post']['body'] !!}

I would suggest printing $data variable and check the whole information this variable holds. You probably want to use other details also from this variable.

I hope you understand how to create a blog with Laravel using a Canvas package. You may learn more about this package on cnvs/canvas.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

6 thoughts on “How to Create a Blog with Laravel

  1. Very thank you for this article.
    in the last part, when we use:
    url($data[‘post’][‘featured_image’])
    if featured_image was null, we got an error.
    better to use this:
    $data[‘post’][‘featured_image’] ? url($data[‘post’][‘featured_image’]) : ”

Leave a Reply

Your email address will not be published. Required fields are marked *