Install and create Laravel project, use the composer create-project command to initialize the blog project and start the development server; 2. Configure the database, set MySQL connection information in the .env file and create a blog database; 3. Create Post model and migration file, define title, content, slug, is_published and other fields and perform migration; 4. Generate PostController resource controller, query published articles in the index method and display them on a page; 5. Use the Blade template engine to create layout and view files, including article lists and details pages; 6. Register resource routes in web.php, and only index and show methods are open for public access; 7. Implement the show method to find and display a single article through slug; 8. Optionally install Laravel Breeze implements authentication, creates an administrator-specific route and controller to process article additions, deletions, modifications and searches; 9. Further optimize functions, such as adding Markdown parsing, image upload, classification tags, SEO support, comment system and search functions; in the end you will get a Laravel blog system with basic functions, MVC architecture, and extensible, ending with complete sentences.
Building a blog with Laravel from scratch is a great way to learn the framework while creating something practical. Laravel provides powerful tools for routing, authentication, database management, and templating—perfect for a blog. Here's a step-by-step guide to help you build a simple but functional blog.

1. Set Up Laravel and Create the Project
First, make sure you have PHP, Composer, and a database (like MySQL) installed.
Run this command in your terminal to create a new Laravel project:

composer create-project laravel/laravel blog
Navigate into the project:
cd blog
Start the development server to verify it works:

php artisan serve
Visit http://localhost:8000
in your browser. You should see the Laravel welcome page.
2. Configure the Database
Open .env
in the root directory and update the database settings:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=blog DB_USERNAME=root DB_PASSWORD=
Make sure you've created the blog
database in MySQL (or your preferred DB).
3. Create the Blog Post Model and Migration
Run the following Artisan command to generate a model and migration for blog posts:
php artisan make:model Post -mf
The -m
creates a migration, and -f
adds a factory (optional).
Open the migration file in database/migrations/xxxx_create_posts_table.php
and define the fields:
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->string('slug')->unique(); $table->boolean('is_published')->default(false); $table->timestamps(); });
Run the migration:
php artisan migrate
4. Build the Post Controller
Generate a controller for handling blog posts:
php artisan make:controller PostController --resource
This creates a resource controller with methods like index
, create
, store
, etc.
Now, go to app/Http/Controllers/PostController.php
and start filling in the logic.
For now, let's set up the index
method to display published posts:
use App\Models\Post; public function index() { $posts = Post::where('is_published', true)->latest()->paginate(5); return view('posts.index', compact('posts')); }
5. Create Blade Views
Create a views directory for posts: resources/views/posts/
Create index.blade.php
:
@extends('layouts.app') @section('content') <h1>Blog Posts</h1> @foreach ($posts as $post) <article> <h2><a href="{{ route('posts.show', $post->slug) }}">{{ $post->title }}</a></h2> <p>{{ Str::limit($post->content, 150) }}</p> <small>Published on {{ $post->created_at->format('M d, Y') }}</small> </article> <hr /> @endforeach {{ $posts->links() }} @endsection
You'll also need a basic layout. Create resources/views/layouts/app.blade.php
:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My Laravel Blog</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-4"> @yield('content') </div> </body> </html>
6. Set Up Routes
Open routes/web.php
and add:
use App\Http\Controllers\PostController; Route::resource('posts', PostController::class)->only(['index', 'show']);
We'll restrict to index
and show
for public access. Admin features (create, edit) can come later.
7. Add the Show Method for Single Posts
In PostController.php
, add the show
method:
public function show($slug) { $post = Post::where('slug', $slug)->where('is_published', true)->firstOrFail(); return view('posts.show', compact('post')); }
Create resources/views/posts/show.blade.php
:
@extends('layouts.app') @section('content') <a href="{{ route('posts.index') }}">← Back to Blog</a> <h1>{{ $post->title }}</h1> <p>{{ $post->content }}</p> <small>Published on {{ $post->created_at->format('M d, Y') }}</small> @endsection
8. Add a Basic Admin Section (Optional)
To create or edit posts, you'll need authentication and an admin area.
Install Laravel Breeze for simple auth:
composer requires laravel/breeze --dev php artisan breeze:install npm install && npm run dev php artisan migrate
Now, protect your admin routes. Generate a controller for admin actions:
php artisan make:controller Admin/PostController
Add routes in web.php
:
use App\Http\Controllers\Admin\PostController as AdminPostController; Route::middleware(['auth'])->prefix('admin')->group(function () { Route::resource('posts', AdminPostController::class); });
Then implement create
, store
, edit
, update
, and destroy
methods in the admin controller, and create corresponding Blade forms.
Add a slug
field when storing posts—use something like:
$post = Post::create([ 'title' => $request->title, 'content' => $request->content, 'slug' => Str::slug($request->title), 'is_published' => $request->is_published, ]);
9. Optional Enhancements
Once the basics are working, consider adding:
- Markdown support using a package like
parsedown
- Image uploads with Laravel's filesystem
- Categories or tags with relationships
- SEO-friendly meta tags
- Comments system (with moderation)
- Search functionality
Final Notes
You now have a working Laravel blog with:
- A public blog listing
- Individual post pages
- A database-backed model
- Simple routing and views
- Optional admin area with authentication
The key is to build incrementally. Start with core features, test each step, then expand.
Basically, that's how you build a blog from scratch in Laravel—no magic, just solid MVC structure and Laravel's elegant syntax.
The above is the detailed content of How to build a blog with Laravel from scratch?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are three ways to add custom validation rules in Laravel: using closures, Rule classes, and form requests. 1. Use closures to be suitable for lightweight verification, such as preventing the user name "admin"; 2. Create Rule classes (such as ValidUsernameRule) to make complex logic clearer and maintainable; 3. Integrate multiple rules in form requests and centrally manage verification logic. At the same time, you can set prompts through custom messages methods or incoming error message arrays to improve flexibility and maintainability.

ToworkeffectivelywithpivottablesinLaravel,firstaccesspivotdatausingwithPivot()orwithTimestamps(),thenupdateentrieswithupdateExistingPivot(),managerelationshipsviadetach()andsync(),andusecustompivotmodelswhenneeded.1.UsewithPivot()toincludespecificcol

Laravelprovidesacleanandflexiblewaytosendnotificationsviamultiplechannelslikeemail,SMS,in-appalerts,andpushnotifications.Youdefinenotificationchannelsinthevia()methodofanotificationclass,andimplementspecificmethodsliketoMail(),toDatabase(),ortoVonage

Dependency injection automatically handles class dependencies through service containers in Laravel without manual new objects. Its core is constructor injection and method injection, such as automatically passing in the Request instance in the controller. Laravel parses dependencies through type prompts and recursively creates the required objects. The binding interface and implementation can be used by the service provider to use the bind method, or singleton to bind a singleton. When using it, you need to ensure type prompts, avoid constructor complications, use context bindings with caution, and understand automatic parsing rules. Mastering these can improve code flexibility and maintenance.

Laravel performance optimization can improve application efficiency through four core directions. 1. Use the cache mechanism to reduce duplicate queries, store infrequently changing data through Cache::remember() and other methods to reduce database access frequency; 2. Optimize database from the model to query statements, avoid N 1 queries, specifying field queries, adding indexes, paging processing and reading and writing separation, and reduce bottlenecks; 3. Use time-consuming operations such as email sending and file exporting to queue asynchronous processing, use Supervisor to manage workers and set up retry mechanisms; 4. Use middleware and service providers reasonably to avoid complex logic and unnecessary initialization code, and delay loading of services to improve startup efficiency.

Methods to manage database state in Laravel tests include using RefreshDatabase, selective seeding of data, careful use of transactions, and manual cleaning if necessary. 1. Use RefreshDatabasetrait to automatically migrate the database structure to ensure that each test is based on a clean database; 2. Use specific seeds to fill the necessary data and generate dynamic data in combination with the model factory; 3. Use DatabaseTransactionstrait to roll back the test changes, but pay attention to its limitations; 4. Manually truncate the table or reseed the database when it cannot be automatically cleaned. These methods are flexibly selected according to the type of test and environment to ensure the reliability and efficiency of the test.

LaravelSanctum is suitable for simple, lightweight API certifications such as SPA or mobile applications, while Passport is suitable for scenarios where full OAuth2 functionality is required. 1. Sanctum provides token-based authentication, suitable for first-party clients; 2. Passport supports complex processes such as authorization codes and client credentials, suitable for third-party developers to access; 3. Sanctum installation and configuration are simpler and maintenance costs are low; 4. Passport functions are comprehensive but configuration is complex, suitable for platforms that require fine permission control. When selecting, you should determine whether the OAuth2 feature is required based on the project requirements.

Laravel simplifies database transaction processing with built-in support. 1. Use the DB::transaction() method to automatically commit or rollback operations to ensure data integrity; 2. Support nested transactions and implement them through savepoints, but it is usually recommended to use a single transaction wrapper to avoid complexity; 3. Provide manual control methods such as beginTransaction(), commit() and rollBack(), suitable for scenarios that require more flexible processing; 4. Best practices include keeping transactions short, only using them when necessary, testing failures, and recording rollback information. Rationally choosing transaction management methods can help improve application reliability and performance.
