Laravel / Laravel Forms and Validation

Using Form Requests for Validation

In this tutorial, we'll delve into Form Requests in Laravel, a feature that encapsulates validation and authorization logic. You'll learn how to use Form Requests to keep your con…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Explores handling form submissions and validating data in Laravel applications.

1. Introduction

Welcome to this tutorial! Our goal is to understand and effectively use Form Requests in Laravel. Form Requests are a powerful feature in Laravel that allows us to encapsulate validation and authorization logic, keeping our controllers lean and our codebase organized.

By the end of this tutorial, you will be able to:

  • Understand what Form Requests are and why they are useful.
  • Create and use Form Requests in your Laravel applications.
  • Understand validation and authorization using Form Requests.

Prerequisites: You should have a basic understanding of PHP programming and some familiarity with Laravel.

2. Step-by-Step Guide

Form Requests in Laravel are special classes that extend the base FormRequest class. These classes are responsible for validating the incoming HTTP request data and also authorize the request.

To create a Form Request class, we use the following artisan command:

php artisan make:request StoreBlogPost

This will create a StoreBlogPost class in the app/Http/Requests directory.

3. Code Examples

Here's an example of a Form Request class:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreBlogPost extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true; // Change this based on your authorization logic
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|max:255',
            'body' => 'required',
        ];
    }
}

In this example, authorize() method is used to determine if the user is authorized to make this request, returning true means any user can make this request. Inside rules() method we define our validation rules for the incoming request data.

To use this Form Request, we simply type-hint it on our controller method:

namespace App\Http\Controllers;

use App\Http\Requests\StoreBlogPost;

class PostController extends Controller
{
    public function store(StoreBlogPost $request)
    {
        // The incoming request is valid...

        // Retrieve the validated input data...
        $validated = $request->validated();
    }
}

4. Summary

In this tutorial, we delved into Form Requests in Laravel, a great feature that allows us to encapsulate validation and authorization logic. We learnt how to create and use Form Requests, and how they help in keeping our controllers lean and our codebase more maintainable.

Additional resources:

5. Practice Exercises

  1. Create a Form Request for a UserRegistration form with the fields: name, email, password.

  2. Extend the above exercise and add authorization logic to only allow guests (non-logged in users) to make the request.

  3. Create a Form Request for a ProductCreation form with fields: name, description, price. Add custom validation messages for each validation rule.

Solutions and explanations for these exercises can be found in the Laravel documentation. Remember, practice is key to mastering any concept. So, keep practicing and happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Name Generator

Generate realistic names with customizable options.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

Image Converter

Convert between different image formats.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help