Laravel - Forms: A Beginner's Guide

Hello there, aspiring developers! As a computer science teacher with years of experience, I'm thrilled to guide you through the exciting world of Laravel forms. Don't worry if you're new to programming – we'll start from the basics and work our way up. By the end of this tutorial, you'll be creating forms like a pro!

Laravel - Forms

What are Laravel Forms?

Before we dive into the code, let's understand what Laravel forms are. Imagine you're filling out a job application online – that's a form! In web development, forms are how we collect information from users. Laravel, our friendly PHP framework, makes creating and handling these forms a breeze.

Why Use Laravel for Forms?

You might be wondering, "Why Laravel?" Well, let me tell you a little story. Back when I was a young developer (yes, dinosaurs roamed the Earth then), creating forms was a tedious process. But Laravel came along like a superhero, making our lives much easier with its powerful tools and security features.

Getting Started

First things first, make sure you have Laravel installed on your system. If you haven't, don't worry! Just follow the official Laravel installation guide, and you'll be up and running in no time.

Example 1: Creating a Simple Contact Form

Let's start with a simple contact form. We'll create a form that asks for a name, email, and message.

Step 1: Create the Route

Open your web.php file in the routes folder and add this line:

Route::get('/contact', 'ContactController@showForm');

This tells Laravel to show our contact form when someone visits the '/contact' URL.

Step 2: Create the Controller

Run this command in your terminal:

php artisan make:controller ContactController

Now, open the newly created ContactController.php file and add this method:

public function showForm()
{
    return view('contact');
}

This method will return our contact form view.

Step 3: Create the View

Create a new file called contact.blade.php in the resources/views folder and add this code:

<form action="/submit-contact" method="POST">
    @csrf
    <div>
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
    </div>
    <div>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
    </div>
    <div>
        <label for="message">Message:</label>
        <textarea id="message" name="message" required></textarea>
    </div>
    <button type="submit">Send</button>
</form>

Let's break this down:

  • @csrf is a Laravel directive that adds a hidden token to prevent cross-site request forgery attacks. Think of it as a secret handshake between your form and Laravel.
  • We've created input fields for name, email, and a textarea for the message.
  • The required attribute ensures users fill out all fields before submitting.

Step 4: Handle Form Submission

Add a new route in web.php:

Route::post('/submit-contact', 'ContactController@submitForm');

Then, add this method to your ContactController:

public function submitForm(Request $request)
{
    $validatedData = $request->validate([
        'name' => 'required|max:255',
        'email' => 'required|email',
        'message' => 'required',
    ]);

    // Process the form data (e.g., save to database, send email)

    return redirect('/contact')->with('success', 'Thank you for your message!');
}

This method validates the form data and redirects back to the contact page with a success message.

Example 2: Creating a Registration Form

Now that we've warmed up, let's create a more complex registration form.

Step 1: Create the Route

Add this to your web.php:

Route::get('/register', 'RegisterController@showForm');
Route::post('/register', 'RegisterController@register');

Step 2: Create the Controller

Run:

php artisan make:controller RegisterController

Add these methods to RegisterController:

public function showForm()
{
    return view('register');
}

public function register(Request $request)
{
    $validatedData = $request->validate([
        'name' => 'required|max:255',
        'email' => 'required|email|unique:users',
        'password' => 'required|min:8|confirmed',
        'date_of_birth' => 'required|date',
        'gender' => 'required|in:male,female,other',
    ]);

    // Create user logic here

    return redirect('/register')->with('success', 'Registration successful!');
}

Step 3: Create the View

Create register.blade.php in your views folder:

<form action="/register" method="POST">
    @csrf
    <div>
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
    </div>
    <div>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
    </div>
    <div>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>
    </div>
    <div>
        <label for="password_confirmation">Confirm Password:</label>
        <input type="password" id="password_confirmation" name="password_confirmation" required>
    </div>
    <div>
        <label for="date_of_birth">Date of Birth:</label>
        <input type="date" id="date_of_birth" name="date_of_birth" required>
    </div>
    <div>
        <label>Gender:</label>
        <input type="radio" id="male" name="gender" value="male" required>
        <label for="male">Male</label>
        <input type="radio" id="female" name="gender" value="female">
        <label for="female">Female</label>
        <input type="radio" id="other" name="gender" value="other">
        <label for="other">Other</label>
    </div>
    <button type="submit">Register</button>
</form>

This form includes various input types: text, email, password, date, and radio buttons.

Form Validation Methods

Here's a table of common Laravel validation methods:

Method Description
required Field must not be empty
email Must be a valid email address
max:value Maximum length
min:value Minimum length
unique:table Must be unique in the specified database table
confirmed Must have a matching field (e.g., password_confirmation)
date Must be a valid date
in:foo,bar,... Must be one of the listed values

Conclusion

Congratulations! You've just created two Laravel forms and learned how to handle them. Remember, practice makes perfect, so keep experimenting with different form types and validation rules.

As we wrap up, let me share a quick anecdote. I once had a student who was terrified of forms – he thought they were these complex, mysterious things. But after a few lessons, he was creating forms for fun! That's the beauty of Laravel – it turns the complex into something enjoyable.

Keep coding, stay curious, and never be afraid to ask questions. Happy form building!

Credits: Image by storyset