Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 67 ยท Projects

Project: A Blog with Authentication in Laravel

Build a Laravel blog step by step with a starter kit, migrations, relationships, policies, validation, Blade views, pagination and Pest tests, plus a runnable core.

This project pulls together most of what you have learned so far. You will build a small blog where visitors read published posts and comment, registered authors write and edit their own posts, and nobody can touch somebody else's work. It is the classic first Laravel application because it uses the whole request path: routes, controllers, validation, Eloquent, authorization, Blade and tests.

Laravel cannot run on this site, so the Laravel code below is read-only: you build it on your own machine (installation shows how). The runnable examples are plain-PHP stand-ins for the core domain: the tables, relationships, pagination and the authorization and validation rules, running on SQLite. If the domain logic is right, the framework code around it is mostly wiring.

flowchart LR
    V["Visitor"] --> B["Blog index<br/>(published, paginated)"]
    V --> S["Post page + comments"]
    A["Author (logged in)"] --> D["Dashboard: my posts"]
    D --> F["Create or edit post<br/>(validated, authorized)"]
    F --> P["Publish or keep as draft"]
    P --> B

Visitors only see published posts; authors manage their own posts through policy-protected routes.

Plan the features

Keep the first version small and finish it:

  1. Authentication: register, log in, log out (from a starter kit).
  2. Posts: title, slug, body, status (draft or published), author.
  3. Public pages: a paginated list of published posts and a page per post.
  4. Authors: create, edit and delete their own posts only.
  5. Comments from logged-in users on published posts.
  6. Tests for the rules that matter.

Step 1: create the project

Terminal
laravel new blog
cd blog

The installer asks for a starter kit. Choose one of the first-party kits that includes authentication (Livewire, React or Vue; see authentication overview) so registration, login, password reset and a profile page already exist. That is the safest way to get authentication right. For SQLite, which is the default database in new projects, you only need php artisan migrate.

Step 2: models and migrations

Terminal
php artisan make:model Post -mfc --policy
php artisan make:model Comment -mf

The flags create the migration (-m), factory (-f), controller (-c) and policy for Post. The posts migration (migrations):

PHP
Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->string('title');
    $table->string('slug')->unique();
    $table->text('body');
    $table->timestamp('published_at')->nullable()->index();
    $table->timestamps();
});

Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->foreignId('post_id')->constrained()->cascadeOnDelete();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->text('body');
    $table->timestamps();
});

A nullable published_at is a neat way to model status: null means draft, a past date means published, and a future date means scheduled. You get "when" and "whether" in one column, and the index makes the list query fast.

The models declare the relationships (relationships) and one query scope (querying):

PHP
class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'slug', 'body', 'published_at'];

    protected function casts(): array
    {
        return ['published_at' => 'datetime'];
    }

    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }

    public function scopePublished(Builder $query): void
    {
        $query->whereNotNull('published_at')->where('published_at', '<=', now());
    }

    public function getRouteKeyName(): string
    {
        return 'slug';          // /posts/my-first-post instead of /posts/1
    }
}

$fillable lists exactly the columns mass assignment may set. Notice that user_id is not in it: the author is always set from the logged-in user, never from the form. Add posts(): HasMany to User as well.

Step 3: routes

PHP
// routes/web.php
Route::get('/', [PostController::class, 'index'])->name('posts.index');

Route::middleware('auth')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::resource('posts', PostController::class)->except(['index', 'show']);
    Route::post('/posts/{post:slug}/comments', [CommentController::class, 'store'])->name('comments.store');
});

// last, so that /posts/create is not captured by the {post} wildcard
Route::get('/posts/{post:slug}', [PostController::class, 'show'])->name('posts.show');

The index and show routes are public. Everything that changes data sits behind the auth middleware. Order matters: GET /posts/create must be registered before the wildcard /posts/{post}, otherwise "create" would be treated as a slug. Check the result with php artisan route:list (routing).

Step 4: validation with a form request

PHP
class StorePostRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;           // authorization is done in the controller via the policy
    }

    protected function prepareForValidation(): void
    {
        $this->merge(['slug' => Str::slug($this->input('slug', $this->input('title', '')))]);
    }

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:150'],
            'slug'  => ['required', 'string', 'max:160', Rule::unique('posts', 'slug')->ignore($this->route('post'))],
            'body'  => ['required', 'string', 'min:20'],
            'publish' => ['sometimes', 'boolean'],
        ];
    }
}

prepareForValidation() normalizes the slug before the rules run, and Rule::unique(...)->ignore() lets an author save an existing post without colliding with itself (form requests).

Step 5: authorization with a policy

The policy answers one question per action: may this user do this to this post? (gates and policies).

PHP
class PostPolicy
{
    public function update(User $user, Post $post): bool
    {
        return $user->id === $post->user_id;
    }

    public function delete(User $user, Post $post): bool
    {
        return $user->id === $post->user_id;
    }
}

Laravel discovers PostPolicy for Post by naming convention. The controller applies it:

PHP
class PostController extends Controller
{
    public function index()
    {
        return view('posts.index', [
            'posts' => Post::published()->with('author')->latest('published_at')->paginate(10),
        ]);
    }

    public function show(Post $post)
    {
        abort_unless($post->published_at?->isPast() || auth()->id() === $post->user_id, 404);

        return view('posts.show', ['post' => $post->load('author', 'comments.user')]);
    }

    public function store(StorePostRequest $request)
    {
        $data = $request->validated();

        $post = $request->user()->posts()->create([
            'title' => $data['title'],
            'slug' => $data['slug'],
            'body' => $data['body'],
            'published_at' => $request->boolean('publish') ? now() : null,
        ]);

        return redirect()->route('posts.show', $post)->with('status', 'Post saved.');
    }

    public function update(StorePostRequest $request, Post $post)
    {
        $this->authorize('update', $post);
        // ...update and redirect
    }

    public function destroy(Post $post)
    {
        $this->authorize('delete', $post);
        $post->delete();

        return redirect()->route('dashboard');
    }
}

Three details deserve attention. with('author') is eager loading, which avoids one extra query per post (N+1). paginate(10) runs a count query plus the page query and gives the view everything it needs for links. And show returns 404 (not 403) for a draft that is not yours, so the existence of a draft does not leak.

Step 6: Blade views

BLADE
{{-- resources/views/posts/index.blade.php --}}
<x-layouts.app title="The blog">
    @foreach ($posts as $post)
        <article>
            <h2><a href="{{ route('posts.show', $post) }}">{{ $post->title }}</a></h2>
            <p>By {{ $post->author->name }} on {{ $post->published_at->toFormattedDateString() }}</p>
            <p>{{ Str::limit(strip_tags($post->body), 160) }}</p>
        </article>
    @endforeach

    {{ $posts->links() }}
</x-layouts.app>

Always print with {{ }}, which escapes HTML, so a malicious title cannot inject a script (Blade). If you ever allow Markdown or HTML in posts, convert and sanitize it on the server and only then output it unescaped. In the post form, add @csrf, show @error('title') messages and repopulate with old('title') (forms).

The core domain, runnable

The framework code above is the wiring. The part that decides whether your blog is correct is small: which posts are visible, how a page of results is computed, who may edit what, and which input is accepted. The two stand-ins below run exactly those rules.

The first uses SQLite to create the tables, apply the "published" scope, eager-load authors with a single query and paginate, like Post::published()->with('author')->latest('published_at')->paginate(3).

PHP Posts, authors and pagination on SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The draft and the post scheduled for July are missing, because published_at is null or in the future. The real paginate() does the same count and limit/offset work, then adds the page links for you.

The second stand-in is the policy and the validation. It uses the same rules as PostPolicy and StorePostRequest, and shows that a draft is hidden from everybody except its author.

PHP Policy, validation and draft visibility

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Step 7: tests

Test the rules, not the framework. Pest feature tests (HTTP and database tests) with factories cover what matters most here:

PHP
use App\Models\Post;
use App\Models\User;

it('lists only published posts', function () {
    Post::factory()->create(['title' => 'Visible', 'published_at' => now()->subDay()]);
    Post::factory()->create(['title' => 'Hidden draft', 'published_at' => null]);

    $this->get('/')
        ->assertOk()
        ->assertSee('Visible')
        ->assertDontSee('Hidden draft');
});

it('lets an author create a post', function () {
    $user = User::factory()->create();

    $this->actingAs($user)
        ->post('/posts', ['title' => 'My first post', 'body' => str_repeat('Hello ', 10), 'publish' => true])
        ->assertRedirect();

    $this->assertDatabaseHas('posts', ['title' => 'My first post', 'user_id' => $user->id]);
});

it('forbids editing somebody else\'s post', function () {
    $post = Post::factory()->create();
    $stranger = User::factory()->create();

    $this->actingAs($stranger)
        ->put("/posts/{$post->slug}", ['title' => 'Hacked', 'body' => str_repeat('x', 30)])
        ->assertForbidden();
});

it('rejects invalid input', function () {
    $this->actingAs(User::factory()->create())
        ->post('/posts', ['title' => '', 'body' => 'short'])
        ->assertSessionHasErrors(['title', 'body']);
});

Put uses(RefreshDatabase::class) in tests/Pest.php for feature tests so every test starts with a clean database. Run them with php artisan test --compact.

Where to go next

Finish the basics first, then extend the project in the direction you want to practice:

  • Comments: a CommentController with the same validation and policy pattern, plus withCount('comments') on the index.
  • Markdown bodies rendered with a sanitizing library.
  • Image uploads for a cover picture (file uploads).
  • Tags with a many-to-many relationship, and filtering by tag.
  • A queued notification to followers when a post is published (queues).
  • Caching the homepage (caching) and a JSON API for the same posts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is user_id left out of Post::$fillable in this project?

    If user_id were fillable, a crafted request could create posts as another user. Creating through $request->user()->posts()->create() sets it safely.
  2. 2. What does a nullable published_at column let you model?

    Null means draft, a date in the past means published, and a future date means scheduled. The published scope compares it with the current time.
  3. 3. Why does show() return 404 instead of 403 for someone else's draft?

    A 404 makes a draft indistinguishable from a post that does not exist, so its existence does not leak.
  4. 4. What is with('author') on the index query for?

    Without eager loading, printing each post's author runs a separate query per post (the N+1 problem). with() loads all needed authors at once.
  5. 5. Which test best proves the policy works?

    Authorization is a rule about who may do what. Act as the wrong user, attempt the action and assert a 403 response.

Summary

  • Start with a starter kit for authentication, then model posts and comments with migrations, relationships and a published scope.
  • Use $fillable carefully, set the author from the logged-in user, and validate with a form request.
  • A policy decides who may update or delete; the controller calls authorize(), and drafts return 404 to others.
  • Eager load, paginate and escape output in Blade.
  • Write Pest tests for visibility, creation, authorization and validation.
  • The core rules are plain domain logic, so they can be run and checked without the framework around them.

Next: Project: A REST API with Sanctum