Building a Blog in Laravel – A Detailed Explanation

Building a Blog in Laravel – A Detailed Explanation

Building a Blog in Laravel – A Detailed Explanation

Creating a blog in Laravel is an excellent way to understand the framework while building a structured and scalable application. This guide will walk through every step in detail, covering Laravel’s MVC architecture, routing, migrations, Eloquent ORM, Blade templating, middleware, and more.


1. Laravel and MVC Architecture

Laravel follows the Model-View-Controller (MVC) architectural pattern. This approach separates the application logic into three components:

  • Model: Handles database interactions. Example: The Post.php model interacts with the posts table.
  • View: The user interface, built using Laravel's Blade Template Engine.
  • Controller: Manages the application logic, processing user requests, and returning appropriate responses.

Example: Implementing MVC in Laravel

1.1. Model – app/Models/Post.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $fillable = ['title', 'content'];
}

1.2. Controller – app/Http/Controllers/PostController.php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

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

1.3. View – resources/views/posts/index.blade.php




    


    

All Blog Posts


    @foreach($posts as $post)
        

{{ $post->title }}


        

{{ $post->content }}


    @endforeach



2. Routing in Laravel

Routes define how requests should be handled in Laravel. They are located in routes/web.php.

Example: Defining a Route

use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'index']);

With this route, when a user visits /posts, the index method in PostController will execute.


3. Composer and Vendor Packages

Laravel uses Composer for package management. Dependencies are stored in the vendor folder.

Installing a Package

composer require spatie/laravel-permission

This adds the spatie/laravel-permission package to vendor/spatie and updates composer.json.

Example: composer.json

{
    "require": {
        "php": "^8.1",
        "laravel/framework": "^10.0",
        "spatie/laravel-permission": "^5.0"
    }
}

4. Database and Migrations

Laravel provides migrations for managing database schemas.

4.1. Creating a Migration

php artisan make:migration create_posts_table

4.2. Editing the Migration – database/migrations/YYYY_MM_DD_create_posts_table.php

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

4.3. Running the Migration

php artisan migrate

5. Seeder – Adding Test Data

Laravel supports seeders for populating test data.

5.1. Creating a Seeder

php artisan make:seeder PostSeeder

5.2. Editing the Seeder – database/seeders/PostSeeder.php

use Illuminate\Database\Seeder;
use App\Models\Post;

class PostSeeder extends Seeder
{
    public function run()
    {
        Post::create([
            'title' => 'First Post',
            'content' => 'This is my first blog post!'
        ]);
    }
}

5.3. Running the Seeder

php artisan db:seed --class=PostSeeder

6. Eloquent ORM – Interacting with the Database

Eloquent ORM simplifies database operations.

Retrieving Data

$posts = Post::all(); // Get all posts
$post = Post::find(1); // Find a post by ID
$latest = Post::latest()->first(); // Get the latest post

Inserting Data

$post = new Post();
$post->title = "New Post";
$post->content = "This is a new post.";
$post->save();

7. Blade Template Engine – Dynamic Views

Blade allows dynamic HTML rendering:

Example

{{ $post->title }}


{{ $post->content }}


Conditional Rendering

@if(count($posts) > 0)
    @foreach($posts as $post)
        

{{ $post->title }}


        

{{ $post->content }}


    @endforeach
@else
    

No posts found.


@endif

8. Middleware – Request Filtering

Middleware filters requests before they reach the controller.

8.1. Creating Middleware

php artisan make:middleware CheckUser

8.2. Editing Middleware – app/Http/Middleware/CheckUser.php

public function handle($request, Closure $next)
{
    if (!auth()->check()) {
        return redirect('/login');
    }
    return $next($request);
}

8.3. Registering Middleware – app/Http/Kernel.php

protected $routeMiddleware = [
    'auth.check' => \App\Http\Middleware\CheckUser::class,
];

8.4. Applying Middleware to Routes

Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('auth.check');

Conclusion

This guide provides a detailed walkthrough of building a Laravel blog. From MVC architecture to middleware, you now have a structured roadmap for developing a Laravel-based blog.

Would you like to extend this guide by adding an Admin Panel for blog management?