Project 1: A Simple Blog Application

In this project, you will build a simple blog application using Laravel. The project will include user authentication and CRUD functionality (Create, Read, Update, Delete) for managing blog posts.


Lesson Outline

  1. Setting Up the Environment
  2. Building User Authentication
  3. Creating the Blog Post Model, Migration, and Controller
  4. Implementing CRUD Functionality
  5. Securing the Application
  6. Enhancing the Blog with Styling and UX

Step 1: Setting Up the Environment

1.1 Install Laravel

Follow the steps from Lesson 19 to install Laravel:

  1. Install Laravel using Composer:
    bash
    composer create-project --prefer-dist laravel/laravel blog
  2. Navigate to the project directory:
    bash
    cd blog

1.2 Configure the Database

  1. Create a new MySQL database named blog.
  2. Update the .env file with your database credentials:
    env
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=blog
    DB_USERNAME=root
    DB_PASSWORD=yourpassword
  3. Run the migration command to ensure Laravel’s default migrations are applied:
    bash
    php artisan migrate

Step 2: Building User Authentication

Laravel provides a built-in authentication system, which you can scaffold using the Laravel Breeze package.

2.1 Install Laravel Breeze

  1. Install Breeze:
    bash
    composer require laravel/breeze --dev
  2. Scaffold the authentication system:
    bash
    php artisan breeze:install
  3. Install the frontend dependencies:
    bash
    npm install && npm run dev
  4. Run the migration command to create the necessary tables for authentication:
    bash
    php artisan migrate

2.2 Test Authentication

  1. Start the Laravel server:
    bash
    php artisan serve
  2. Open your browser and navigate to http://localhost:8000.
  3. Register a new user and log in to verify that the authentication system works.

Step 3: Creating the Blog Post Model, Migration, and Controller

3.1 Create a Blog Post Model and Migration

  1. Run the Artisan command to generate the model and migration:
    bash
    php artisan make:model Post -m
  2. Open the migration file in database/migrations/ and define the schema:
    php
    public function up()
    {
    Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->timestamps();
    });
    }
  3. Run the migration:
    bash
    php artisan migrate

3.2 Create a Controller for Posts

Generate a resource controller:

bash
php artisan make:controller PostController --resource

The PostController will handle CRUD operations for blog posts.


Step 4: Implementing CRUD Functionality

4.1 Define Routes

Open routes/web.php and define the routes for the Post resource:

php

use App\Http\Controllers\PostController;

Route::middleware([‘auth’])->group(function () {
Route::resource(‘posts’, PostController::class);
});


4.2 Add Methods in the PostController

Show All Posts (Index)

php
public function index()
{
$posts = Post::where('user_id', auth()->id())->get();
return view('posts.index', compact('posts'));
}

Show Form to Create a Post

php
public function create()
{
return view('posts.create');
}

Store a New Post

php
public function store(Request $request)
{
$request->validate([
'title' => 'required|max:255',
'content' => 'required',
]);
Post::create([
‘title’ => $request->title,
‘content’ => $request->content,
‘user_id’ => auth()->id(),
]);

return redirect()->route(‘posts.index’)->with(‘success’, ‘Post created successfully.’);
}


Edit an Existing Post

php
public function edit(Post $post)
{
if ($post->user_id !== auth()->id()) {
abort(403);
}
return view(‘posts.edit’, compact(‘post’));
}


Update a Post

php
public function update(Request $request, Post $post)
{
if ($post->user_id !== auth()->id()) {
abort(403);
}
$request->validate([
‘title’ => ‘required|max:255’,
‘content’ => ‘required’,
]);

$post->update($request->only([‘title’, ‘content’]));

return redirect()->route(‘posts.index’)->with(‘success’, ‘Post updated successfully.’);
}


Delete a Post

php
public function destroy(Post $post)
{
if ($post->user_id !== auth()->id()) {
abort(403);
}
$post->delete();

return redirect()->route(‘posts.index’)->with(‘success’, ‘Post deleted successfully.’);
}


4.3 Create Blade Templates

List All Posts (posts/index.blade.php)

html
<h1>My Blog Posts</h1>
<a href="{{ route('posts.create') }}">Create New Post</a>
<ul>
@foreach ($posts as $post)
<li>
<a href="{{ route('posts.edit', $post) }}">{{ $post->title }}</a>
<form action="{{ route('posts.destroy', $post) }}" method="POST">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
</li>
@endforeach
</ul>

Create Post Form (posts/create.blade.php)

html
<h1>Create New Post</h1>
<form action="{{ route('posts.store') }}" method="POST">
@csrf
<label for="title">Title:</label>
<input type="text" name="title" required><br>
<label for="content">Content:</label>
<textarea name="content" required></textarea><br>
<button type="submit">Save</button>
</form>

Edit Post Form (posts/edit.blade.php)

html
<h1>Edit Post</h1>
<form action="{{ route('posts.update', $post) }}" method="POST">
@csrf
@method('PUT')
<label for="title">Title:</label>
<input type="text" name="title" value="{{ $post->title }}" required><br>
<label for="content">Content:</label>
<textarea name="content" required>{{ $post->content }}</textarea><br>
<button type="submit">Update</button>
</form>

Step 5: Securing the Application

  1. Protect Routes:
    • Ensure routes are protected with the auth middleware.
    • Use abort(403) to prevent unauthorized access to posts.
  2. Validation:
    • Validate user input to prevent invalid or malicious data.

Activities and Exercises

  1. Enhance the Blog:
    • Add categories to posts.
    • Allow posts to be marked as “published” or “draft.”
  2. Styling:
    • Use Bootstrap or Tailwind CSS to style the blog.
  3. Search:
    • Implement a search feature to find posts by title or content.

Assignment

  1. Extend the blog application to include:
    • Image uploads for posts.
    • Pagination for the list of posts.
    • A public page where non-authenticated users can view published posts.
  2. Write a test case to ensure only authenticated users can create, edit, or delete posts.

Summary

In this project, you:

  1. Built a blog application with Laravel.
  2. Implemented user authentication.
  3. Added CRUD functionality for blog posts.
  4. Secured routes and user permissions.

This project demonstrates the power of Laravel for building real-world applications. Let me know if you’d like to explore advanced features or additional enhancements!


Comments

Leave a Reply

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