Laravel Forms And Validation Rules With Example

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

This tutorial explains Laravel Forms and Form Validation Rules. Learn about different form elements with examples:

In the Laravel Database tutorial of Laravel Tutorial series, we learned about Database handling, Migrations, Seeding, Raw SQL Queries, Eloquent Models, Eloquent Relationships, Artisan and Tinker.

Forms are an essential feature when developing a web-based application. It is difficult to even think about a web application without having a form. Validation is a critical factor when creating a form, and without proper validation these are useless.

There are several methods to build a form. In this tutorial, we have discussed one such method. This tutorial also refreshes your HTML knowledge related to forms.

Laravel Forms and Validation

In this tutorial, we have covered Laravel forms and Laravel validation rules. For all the examples, we have used Laravel version 7.

Laravel Forms

Prerequisites

To proceed, you need to be familiar with the following concepts:

#1) Bootstrap

We have used Bootstrap as the CSS framework in this tutorial, assuming that you are familiar with the Bootstrap framework. Visit this link to know more about Bootstrap.

#2) Laravel installation and creating a new project

Please refer to the Laravel Introduction Tutorial to understand how to install Laravel and create a new project.

#3) Laravel database configuration

Please refer to the Laravel Database Tutorial to have the basic idea of the Laravel database concept.

CSRF Token

CSRF Stands for Cross-Site Request Forgery. CSRF token is used to protect the web application from CSRF attacks. These token contains a unique value generated by the server-side of the application, which is sent to the client-side of the application. Further, it helps to verify whether an authenticated user is sending the request to the application.

We use this token when the developer creates a form as shown below:

<form action="#" method="post">
@csrf
...
</form

Form Elements

The following list shows some of the form elements that we can use while creating a form.

  • Label
  • Text input
  • Default input
  • Number input
  • Date input
  • File input
  • Hidden input
  • Textarea
  • Email input
  • Password input
  • Drop-down list or select box
  • Radio button input
    • Radio button input
    • Radio button input that is checked
  • Checkbox
    • Checkbox input
    • Checkbox input that is checked
  • Button
    • Normal button
    • Submit button
    • Rest button

We can use the following code snippets as a reference when creating a form.

#1) Label

Description: A label represents the caption for the form element.

Example: Generating a label for the first name.

<label for="first_name">First Name</label>

#2) Text Input

Description: A text input field is a single line input field that allows the user to enter text.

Example: Generating a text input field for the first name.

<input type="text" name="fname" id="fname">

#3) Default Input

Description: A default input field allows the developer to insert an input field with a default value. The user can either submit the form with the default value or change the value.

Example: Generating an input field for the first name with default value John Doe.

<input type="text" name="fname" id="fname" value="John Doe">

#4) Number Input

Description: The number of input field allows the user to enter a numeric value.

Example: Generating a number input field for age.

<input type="number" name="age" id="age">

#5) Date Input

Description: A date input field allows the user to select a date.

Example: Generating a date input field for the birth date.

<input type="date" name="bday" id="bday">

#6) File Input

Description: A file input field allows the user to upload a file.

Example: Generating a file select field for certificate copy upload.

<input type="file" name="certcopy" id="certcopy">

#7) Hidden Input

Description: A hidden input field allows the developer to add data when the user submits the form, and the user cannot see or modify these data.

Example: Generating a hidden input field for student id that has the value 220.

<input type="hidden" id="stu_id" name="stu_id" value="220">

#8) Textarea

Description: A textarea allows the user to enter a long text. It may contain multiple lines of text.

Example: Generating a textarea for address.

<textarea name="address" id="address" rows="4"></textarea>

#9) Email Input

Description: An email input field allows the user to enter an email address. It automatically validates the email format.

Example: Generating an email input field.

<input type="email" name="email" id="email">

#10) Password Input

Description: A password input field allows the user to enter a password. The entering characters are masked.

Example: Generating a password input field.

<input type="password" name="password" id="password">

#11) Drop-down List or Select Box

Description: A drop-down list or select box allows the user to select an option from a list of options.

Example: Generating a drop-down list for the title.

<label>Title</label>
<select name="title" id="title">
<option>--</option>
<option value="mr.">Mr.</option>
<option value="ms.">Ms.</option>
<option value="dr.">Dr.</option>
</select>

#12) Radio Button Input

a) Radio Button Input

Description: A radio button allows the user to select a single option from a list of two or more mutually exclusive options.

Example: Generating a radio button input field for gender.

<label>Gender</label>
<input type="radio" value="Male" id="male" name="gender">
<label for="male">Male</label>
<input type="radio" value="Female" id="female" name="gender">
<label for="female">Female</label>	

b) Radio Button Input that is Checked

Description: This allows the developer to insert a radio button input field that is checked.

Example: Generating a radio button input field for gendermale option is checked.

<label>Gender</label>
<input type="radio" value="Male" id="male" name="gender" checked>
<label for="male">Male</label>
<input type="radio" value="Female" id="female" name="gender">
<label for="female">Female</label>

#13) Checkbox Input

a) Checkbox Input

Description: A checkbox allows the user to select one or more options from a given set of options.

Example: Generating a checkbox input field for colours.

<label>Colours</label>
<input type="checkbox" value="Red" id="colour1" name="colour1">
<label for="red">Red</label>
<input type="checkbox" value="Yellow" id="colour2" name="colour2">
<label for="yellow">Yellow</label>
<input type="checkbox" value="Green" id="colour3" name="colour3">
<label for="green">Green</label>	

b) Checkbox Input that is Checked

Description: This allows the developer to insert a checkbox input field that is checked.

Example: Generating a checkbox input field for coloursred is checked.

<label>Colours</label>
<input type="checkbox" value="Red" id="colour1" name="colour1" checked>
<label for="red">Red</label>
<input type="checkbox" value="Yellow" id="colour2" name="colour2">
<label for="yellow">Yellow</label>
<input type="checkbox" value="Green" id="colour3" name="colour3">
<label for="green">Green</label>	

#14) Buttons

Three types of buttons can be used when creating Laravel forms.

  • Normal button
  • Submit button
  • Reset button

a) Normal Button

Description: A normal button is a clickable button.

Example: Generating a normal button.

<input type="button" value="Click!" onclick="msg()">

b) Submit Button

Description: A submit button allows the user to submit form data to the server-side of the application.

Example: Generating a submit button.

<input type="submit" name="submit" value="Submit">

c) Reset Button

Description: A reset button allows the user to set form fields to its original values.

Example: Generating a reset button.

<input type="reset" name="reset" value="Reset">

Laravel Validation Rules

The following list shows some Laravel validation rules:

Note: Refer to the official documentation of Laravel validation to see the full list of validation. Some of the important rules are listed below.

#1) Before Or Equal (Date)before_or_equal:date

This validation rule only allows using a value preceding or equal to the given date.

#2) Betweenbetween:min,max

This validation rule only allows using a size between the given min and max.

#3) Datedate

This validation rule only allows using a valid, non-relative date according to the strtotime PHP function.

#4) Date Formatdate_format:format

Under this validation rule, the field must match the given format.

#5) Differentdifferent:field

Under this validation rule, the field must have a different value than the field.

#6) Distinctdistinct

When working with arrays, under this validation rule, the field must not have any duplicate values.

#7) Emailemail

Under this validation rule, the field must be formatted as an email address.

#8) Image (File)image

Under this validation rule, the field must be an image (jpeg, png, bmp, gif, svg, or webp).

#9) Nullablenullable

Under this validation rule, the field must be null.

#10) Numericnumeric

Under this validation rule, the field must be numeric.

#11) Regular Expressionregex:pattern

Under this validation rule, the field must match the given regular expression.

#12) Requiredrequired

Under this validation rule, the field must be present in the input data and not empty.

#13) Sizesize:value

Under this validation rule, the field must have a size matching the given value.

#14) Sometimessometimes

This validation rule runs validation checks against a field only if that field is present in the input array.

#15) URLurl

Under this validation rule, the field must be a valid URL.

Laravel Forms Example With Laravel Validation

In this example, we are going to create a student registration form with basic Laravel validation.

Step 1: Install a fresh Laravel project.

Step 2: Connect your project to the database.

Step 3: Create xxxx_xx_xx_xxxxxx_create_students_table migration and the Student model.

Open the xxxx_xx_xx_xxxxxx_create_students_table.php file and modify the existing code as shown below:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title',10);
            $table->string('name');
            $table->date('bday');
            $table->integer('age');
            $table->string('gender',10);
            $table->string('phone');
            $table->string('address');
            $table->string('email');
            $table->string('password');
            $table->boolean('t&c');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}

Open the Student.php file and modify the existing code as shown below:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    public $fillable = ['title', 'name', 'bday', 'age', 'gender','phone', 'address', 'email', 'password', 't&c'];
}

Step 4: Run the following command in the command prompt to run migrations.

php artisan migrate

Step 5: Add the following two routes to the routes/web.php file.

Route::get('student/create','StudentController@create')->name('student.create');
Route::post('student/create','StudentController@store')->name('student.store');

Step 6: Create StudentController and modify the existing code as shown below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Student;

class StudentController extends Controller
{
    public function create()

    {
        return view('create');
    }

    public function store(Request $request)

    {
        $input = $request->all();

        $request->validate([
            'title' => 'required',
            'name' => 'required|max:255',
            'bday' => 'required|date',
            'age' => 'required|numeric',
            'gender' => 'required',
            'phone' => 'required|min:10',
            'address' => 'required|max:255',
            'email' => 'required|email|max:255',
            'password' => 'required|min:6|max:255',
            't&c' => 'required',
        ]);

        $input['password'] = bcrypt($input['password']);
        Student::create($input);

        return back()->with('success','Successfully registered a new student!');

    }

}

Step 7: Create the relevant view file (create.blade.php) and add the following code.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 7 Forms Tutorial</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
 </head>
<body>
<div class="container mt-3 mb-3">

    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    @if ($message = Session::get('success'))
        <div class="alert alert-success alert-block">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <strong>{{ $message }}</strong>
        </div>
    @endif

    <h3>Student Registration Form</h3>
    <form action="{{ route('student.store') }}" method="POST" enctype="multipart/form-data">

        @csrf

        <div class="form-group">
            <label>Title</label>
            <select class="form-control" name="title" id="title">
                <option value="">--</option>
                <option value="mr">Mr.</option>
                <option value="ms.">Ms.</option>
            </select>
        </div>

        <div class="form-group">
            <label>Name</label>
            <input type="text" class="form-control" name="name" id="name">
        </div>

        <div class="form-group">
            <label>Birth Date</label>
            <input type="date" class="form-control" name="bday" id="bday">
        </div>

        <div class="form-group">
            <label>Age</label>
            <input type="number" class="form-control" name="age" id="age">
        </div>

        <div class="form-group">
            <label>Gender</label>
                <div class="custom-control custom-radio custom-control-inline">
                    <input class="custom-control-input" type="radio" value="Male" id="male" name="gender">
                    <label class="custom-control-label" for="male">Male</label>
                </div>
                <div class="custom-control custom-radio custom-control-inline">
                    <input class="custom-control-input" type="radio" value="Female" id="female" name="gender">
                    <label class="custom-control-label" for="female">Female</label>
                </div>
        </div>

        <div class="form-group">
            <label>Phone</label>
            <input type="text" class="form-control" name="phone" id="phone">
        </div>

        <div class="form-group">
            <label>Address</label>
            <textarea class="form-control" name="address" id="address" rows="4"></textarea>
        </div>

        <div class="form-group">
            <label>Email</label>
            <input type="email" class="form-control" name="email" id="email">
        </div>

        <div class="form-group">
            <label>Password</label>
            <input type="password" class="form-control" name="password" id="password">
        </div>

        <div class="form-group">
            <div class="form-check">
                <input class="form-check-input" type="checkbox" value="1" id="t&c" name="t&c">
                <label class="form-check-label">
                    I agree to the terms and conditions.
                </label>
            </div>
            </div>

        <input type="reset" name="reset" value="Reset" class="btn btn-dark">
        <input type="submit" name="submit" value="Submit" class="btn btn-dark">

    </form>
</div>
</body>

</html>

Step 8: Run the project on the browser. It will produce an output similar to the below screenshot.

Run the project on the browser

It is time to play around with this form. If you fill the form with invalid values, you will get validation errors. If you fill the form correctly and submit, then you will get a success message, and values will get saved in the database.

Conclusion

Laravel forms help developers to collect data from clients or site visitors. The developer must create forms with proper validation. Otherwise, forms may not be useful as they are. We have discussed important Laravel Form Validation rules in this tutorial.

We hope you found this tutorial helpful! Hope to see you again in the next tutorial where we will discuss file uploading, sending emails, sessions, authentication, and authorization.

Happy learning!

<< PREV Tutorial | NEXT Tutorial>>

Was this helpful?

Thanks for your feedback!

Leave a Comment