Working with forms in Laravel

In a post written what feels like months ago identified a weakness in forms, so here I am practicing and improving.

Creating a form in Laravel to allow users to submit a blog post involves several steps. Here, I'll provide a simplified example of creating a form using Laravel's Blade templating engine and handling the form submission. Please note that this example assumes you have a basic Laravel application set up.

Step 1: Create the BlogPostController

First, create a controller to handle blog post creation:

artisan make:controller BlogPostController

This command will generate a new controller in the app/Http/Controllers directory.

Step 2: Define Routes

In the web.php file, define routes for showing the form and submitting the form data:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BlogPostController;

Route::get('/blog/create', [BlogPostController::class, 'create']);
Route::post('/blog', [BlogPostController::class, 'store']);

There is also this super cool new resources technique that I learned where Laravel expects to be passed CRUD verbs.

I used it later in the project when setting up categories. Saves me from haveing to create an individual for index, edit, show etc.

Route::resource('categories', CategoriesController::class);

Step 3: Create the Form

Create a Blade view for your form. For example, create create.blade.php in the resources/views directory:

@extends('layouts.app')

@section('content')
    <div class="container">
        <h1>Create a Blog Post</h1>

        <form method="post" action="/blog">
            @csrf

            <div class="form-group">
                <label for="title">Title</label>
                <input type="text" name="title" class="form-control" required>
            </div>

            <div class="form-group">
                <label for="content">Content</label>
                <textarea name="content" class="form-control" rows="4" required></textarea>
            </div>

            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
@endsection

This Blade view displays a form with fields for the title and content of the blog post.

Step 4: Handle the Form Submission

In the BlogPostController, implement the create and store methods:

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

public function store(Request $request)
{
    // Validate the form data
    $validatedData = $request->validate([
        'title' => 'required|max:255',
        'content' => 'required',
    ]);

    // Create a new blog post
    $blogPost = new BlogPost();
    $blogPost->title = $validatedData['title'];
    $blogPost->content = $validatedData['content'];
    $blogPost->save();

    return redirect('/blog')->with('success', 'Blog post created successfully!');
}

In the store method, we validate the form data, create a new BlogPost model instance, and save it to the database.

Don't forget to import the necessary classes at the top of the controller file:

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

Step 5: Display a Confirmation Message

I can display a success message in your create.blade.php view to confirm that the blog post was created successfully. For example:

@if (session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif

This code checks if there's a 'success' variable in the session, and if so, it displays a success message.