How To Create Manual Form Validation In Laravel Framework

admin_img Posted By Bajarangi soft , Posted On 17-09-2020

If you do not want to use a validate() method on the request, you may create the validator instance manually using the Validator facade. The make method on the facade generates a new validator instance.

How To Create Manual Validators In Laravel With Example

If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{
    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                ->withErrors($validator)
                ->withInput();
        }

        // Store the blog post...
    }
}
 

The first argument passed to the make method is the data under validation. The second argument is the validation rules that should be applied to the data.

After checking if the request validation failed, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The withErrors method accepts a validator, a MessageBag, or a PHP array.

 

Automatic Redirection

If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the request's validate method, you may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an AJAX request, a JSON response will be returned:
 
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();

You may use the validateWithBag method to store the error messages in a named error bag if validation fails:
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validateWithBag('post');
 

Named Error Bags

If you have multiple forms on a single page, you may wish to name the MessageBag of errors, allowing you to retrieve the error messages for a specific form. Pass a name as the second argument to withErrors:
return redirect('register')
    ->withErrors($validator, 'login');
 


You may then access the named MessageBag instance from the $errors variable:
 

{{ $errors->login->first('email') }}
 

After Validation Hook

The validator also allows you to attach callbacks to be run after validation is completed. This allows you to easily perform further validation and even add more error messages to the message collection. To get started, use the after method on a validator instance:

$validator = Validator::make(...);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add('field', 'Something is wrong with this field!');
    }
});

if ($validator->fails()) {
    //
}
 

For Example(1)

Open web.php file and implement below code in it.

Route::get('post/create', 'PostController@create');

Route::post('post', 'PostController@store');


Create PostController and implement below code in it.
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{
    public function Create(){

        return view('create');
    }
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                ->withErrors($validator)
                ->withInput();
        }

        // Store the blog post...
        return 'done';
    }
}


Create and implement below code in create.blade.php file
<!DOCTYPE html>
<html>
<head>
    <title>Manual Form Validation In Laravel</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>Manual Form Validation In Laravel</h1>
    </div>
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    <div class="form-group col-sm-2">

    </div>
    <div class="form-group col-sm-8">
        <div class="well">
            <form method="post" action="{{url('post')}}">
                @csrf
                <div class="form-group col-sm-12">
                    <label for="title">Post Title</label>

                    <input id="title" type="text" class="form-control @error('title') is-invalid @enderror">

                    @error('title')
                    <div class="alert alert-danger">{{ $message }}</div>
                    @enderror
                </div>
                <div class="form-group col-sm-12">
                    <label>Body</label>
                    <textarea  class="form-control @error('body') is-invalid @enderror" type="textarea" name="body" ></textarea>
                    @error('body')
                    <div class="alert alert-danger">{{ $message }}</div>
                    @enderror
                </div>
                <div class="form-group text-center">
                    <input  class="btn btn-primary" type="submit" >
                </div>
            </form>
            <div class="form-group col-sm-2"></div>
        </div>
    </div>
    <br>
</div>
</body>
</html>


To see output pass below url in google chrome
 
http://localhost/laraveldemoproject/public/post/create

 

Related Post