Skip to main content
Laravel Basics Tutorial
CHAPTER 07 Beginner

Forms and Request Handling

Updated: May 14, 2026
20 min read

# CHAPTER 7

Forms and Request Handling

1. Introduction

Web applications are interactive. Users must be able to log in, upload files, and post comments. All of this is done through HTML forms. However, handling forms in core PHP using $POST and $GET is tedious and insecure. In this chapter, we will learn how Laravel's elegant Request object captures user data, and how the built-in @csrf directive provides impenetrable security.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Build an HTML form in Blade.
  • Use the @csrf directive to prevent Cross-Site Request Forgery.
  • Capture form data in a Controller using the Request object.
  • Redirect users back with success or error messages.

3. Beginner-Friendly Explanation

Imagine a user sending a letter (the Form) to the backend. In core PHP, the backend developer has to manually open the envelope, dig through it, and pull out the data using variables like $_POST['email']. It's messy. In Laravel, there is a specialized assistant named the Request Object. When the letter arrives, the Request assistant opens it, organizes all the data perfectly, and hands it to the Controller on a silver platter. You just ask the assistant: *"Give me the email address,"* and it hands it to you.

4. Creating the Blade Form

Let's build a simple form to create a new blog post.

resources/views/create.blade.php

html
1234567891011121314
<!-- The action points to our Named Route -->
<form method="POST" action="{{ route(&#039;posts.store') }}">
    
    <!-- CRITICAL: You MUST include this directive in every POST form! -->
    @csrf

    <label>Post Title:</label>
    <input type="text" name="title">

    <label>Post Content:</label>
    <textarea name="content"></textarea>

    <button type="submit">Publish</button>
</form>

5. What is @csrf?

If you forget @csrf, Laravel will crash and throw a 419 Page Expired error when you click submit. *Why?* Laravel is fiercely protective. Without @csrf, a malicious website could secretly submit a POST request to your app, pretending to be a logged-in user (a CSRF attack). The @csrf directive generates a hidden, encrypted token. When the form is submitted, Laravel checks the token. If it matches, the form is legitimate. If not, the request is blocked.

6. Defining the Routes

We need two routes: one to show the form (GET), and one to process the data (POST).

routes/web.php

php
1234567
use App\Http\Controllers\PostController;

// Shows the HTML form
Route::get(&#039;/posts/create', [PostController::class, 'create'])->name('posts.create');

// Catches the submitted data
Route::post(&#039;/posts', [PostController::class, 'store'])->name('posts.store');

7. Handling the Request in the Controller

Here is where the magic of Laravel's Request object shines.

app/Http/Controllers/PostController.php

php
12345678910111213141516171819202122
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class PostController extends Controller
{
    // The Store method automatically receives the Request object
    public function store(Request $request)
    {
        // 1. Fetching data is incredibly clean
        $title = $request->input(&#039;title');
        $content = $request->input(&#039;content');
        
        // Alternatively, fetch ALL data at once as an array
        $all_data = $request->all();

        // (We will save this to the database in later chapters)

        // 2. Redirect the user back to the homepage with a success message!
        return redirect(&#039;/')->with('success', 'Post published successfully!');
    }
}

8. Flashing Session Data (Success Messages)

Notice the with('success', 'message') method on the redirect. This "flashes" data to the session. It exists for *exactly one page load* so you can show a success banner, and then it deletes itself.

In home.blade.php to display the message:

html
12345
@if (session(&#039;success'))
    <div class="alert alert-success">
        {{ session(&#039;success') }}
    </div>
@endif

9. Best Practices

  • Don't Use $POST: Never use core PHP superglobals like $POST or $FILES inside a Laravel controller. Always use the $request object (e.g., $request->file('image')). It provides automatic security filtering and formatting that you bypass if you use raw PHP.

10. Common Mistakes

  • The 419 Error: As mentioned, 99% of the time a beginner gets a "419 Page Expired" error upon form submission, it is because they forgot to include the @csrf directive inside the <form> tags in their Blade file.

11. Exercises

  1. 1. Explain the mechanism behind a CSRF attack and how Laravel's @csrf directive neutralizes it.

12. Coding Challenges

  • Challenge: Write the Controller code required to check if a user checked a specific checkbox named newsletter. Use the $request->has('newsletter') boolean method.

13. MCQs with Answers

Question 1

What error will Laravel throw if you submit a POST form without including the @csrf directive?

Question 2

When returning a redirect in Laravel, what does the ->with('key', 'message') method do?

14. Interview Questions

  • Q: Explain how Dependency Injection works in Laravel Controller methods specifically regarding the Request $request object.
  • Q: Why is relying on the $request->all() method dangerous if you are bulk-inserting data into a database? (Hint: Mass Assignment Vulnerabilities).

15. FAQs

Q: Do I need @csrf for GET requests? A: No. GET requests are strictly used to retrieve data (like viewing a profile). Because they do not modify the database or mutate state, they do not require CSRF protection.

16. Summary

In Chapter 7, we made our application interactive. By capturing user input via the Request object, we eliminated the need for messy $
POST arrays, writing clean, object-oriented code. Most importantly, we secured our application by embedding the @csrf token into our forms, guaranteeing that all incoming data originated from a legitimate user on our website.

17. Next Chapter Recommendation

Our forms are sending data, but we have nowhere to save it yet. We need a database. Proceed to Chapter 8: Database Configuration and Migrations.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·