Form validation is a client type of validation that is required in any form. Whether you are creating a contact form, lead form, or any kind of registration. It always required a completed and validated data. If you are taking inputs from the users, you always want that user is genuine. Also, every information must relate to the user and it should be correct. Hence, in this tutorial, I will be showing you the Laravel 8 form validation. I will be starting from the scratch.
Prerequisites
For creating this form validation project in Laravel 8, we will require the following tools and version.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
Create Project For Laravel 8 Form Validation
For validating a form in Laravel 8, I will create a basic registration form. Then for that form inputs, I will put the validation rules in the controller. Also, I will be displaying out the validation errors in the form. So, this is a basic overview of this project.
Now, we will be creating the Laravel 8 project using the composer. So, use the terminal or command prompt and hit the below command.
composer create-project --prefer-dist laravel/laravel form-validation
It will take a couple of minutes to ready the setup.
When the project is ready, let’s create and configure a database for this.
Laravel 8 CRUD Application Tutorial From Scratch
Create and Configure Database
For the database, I will be using the MySQL command line. So, create a database by giving a name there.
CREATE DATABASE laravel8_form_validation;
Now, we have the database ready. In the next step, we’ll connect with the Laravel 8 Form validation project.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel8_form_validation
DB_USERNAME=root
DB_PASSWORD=root
You will have to replace the DB_USERNAME and DB_PASSWORD. Then the project is good to go with the database.
How to Implement Yajra DataTable in Laravel 7
Create a Model and Migration
I will be creating a form with some specific inputs. When the form validation will pass, I will be storing the value to the database table.
Here, I will be using the default model and the migration available in the project. Laravel provides a model and migration for the User. So, let’s use it with some modifications in migration.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('email')->unique();
$table->string('phone')->unique();
$table->string('address')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
I have added some fields in the default migration file. Now, moving to the next step, and adding the fillable data in the User.php (model).
Laravel 7 Yajra DataTable with Server Side Processing
Add Fillable Data in User Model
In Laravel 8, we have a separate folder for the models file. So, you can find the Models directory inside the app. Add the below fillable data there.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'phone', 'address'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
After specifying the fillable data, let’s migrate the table.
php artisan migrate
The above command will migrate all the migration file in the database.
Create a CRUD App in React.js Using Laravel 7 RESTful API
Create a Controller For Form Validation
For handling the form validation in Laravel 8, we will require a controller. The controller will read out the inputs from the view (form). In the controller we will write the validation rules as well.
php artisan make:controller UserController
The above command will create a controller file named UserController.php.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function create() {
return view('registration-form');
}
// ----------- [ Form validate ] -----------
public function store(Request $request) {
$request->validate(
[
'name' => 'required|string|max:20',
'email' => 'required|email|unique:users,email',
'phone' => 'required|numeric|min:10',
'password' => 'required|alpha_num|min:6',
'confirm_password' => 'required|same:password',
'address' => 'required|string'
]
);
$dataArray = array(
"name" => $request->name,
"email" => $request->email,
"phone" => $request->phone,
"address" => $request->address,
"password" => $request->password
);
$user = User::create($dataArray);
if(!is_null($user)) {
return back()->with("success", "Success! Registration completed");
}
else {
return back()->with("failed", "Alert! Failed to register");
}
}
}
For the above functions, we have to create the routes in the web.php file. As per the update in Laravel 8, you can create the route as showing below. Now, the controller will be imported as a namespace in the route file.
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::get("user", [UserController::class, 'create']);
Route::post("user/create", [UserController::class, 'store']);
After creating the routes, let’s create a view for getting the user inputs.
How to Implement Column Filter in Laravel 7 Yajra Datatable
Create View
For the registration form, we will have to create a view. So, in the resources/views, we will create a registration-form.blade.php file.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 8 Form Validation - Programming Fields</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5">
<form action="{{url('user/create')}}" method="POST">
@csrf
<div class="row">
<div class="col-xl-6 m-auto">
<div class="card shadow">
@if(Session::has('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
{{Session::get('success')}}
</div>
@elseif(Session::has('failed'))
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
{{Session::get('failed')}}
</div>
@endif
<div class="card-header">
<h4 class="card-title font-weight-bold"> Laravel 8 Form Validation </h4>
</div>
<div class="card-body">
<div class="form-group">
<label for="name"> Name <span class="text-danger"> * </span> </label>
<input type="text" name="name" class="form-control" value="{{old('name')}}" />
{!!$errors->first("name", "<span class='text-danger'>:message</span>")!!}
</div>
<div class="form-group">
<label for="email"> Email <span class="text-danger"> * </span> </label>
<input type="text" name="email" class="form-control" value="{{old('email')}}" />
{!!$errors->first("email", "<span class='text-danger'>:message</span>")!!}
</div>
<div class="form-group">
<label for="phone"> Phone <span class="text-danger"> * </span></label>
<input type="text" max="10" name="phone" class="form-control" value="{{old('phone')}}" />
{!!$errors->first("phone", "<span class='text-danger'>:message</span>")!!}
</div>
<div class="form-group">
<label for="password"> Password <span class="text-danger"> * </span></label>
<input type="password" name="password" class="form-control" value="{{old('password')}}" />
{!!$errors->first("password", "<span class='text-danger'>:message</span>")!!}
</div>
<div class="form-group">
<label for="confirm_password"> Confirm Password <span class="text-danger"> * </span></label>
<input type="password" name="confirm_password" class="form-control" value="{{old('confirm_password')}}" />
{!!$errors->first("confirm_password", "<span class='text-danger'>:message</span>")!!}
</div>
<div class="form-group">
<label for="address"> Address <span class="text-danger"> * </span></label>
<input type="text" name="address" class="form-control" value="{{old('address')}}" />
{!!$errors->first("address", "<span class='text-danger'>:message</span>")!!}
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Register </button>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Here, view is ready to serve the application. So, let’s check the result.
When you will submit the form without filling up any details, then you will have the following error messages.
But, when you will fill up the detail as required, you will pass the validation criteria.
How to Upload Image in Laravel 8 with Validation
Once the validation passed, you will get the success response on submitting the form.
Conclusion
This is a basic demonstration of form validation using Laravel 8. You can pass many fields as per your form. You can change the validation error message by defining the custom rules. This can help you for creating any type of form validation. If you stuck in any kind of issues in Laravel then please let me know. I will help you.
Leave a Reply