Laravel Validation: Manually Creating Validators

<?php

namespace App\Http\Controllers;

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

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...
    }
}

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

Automatic Redirection

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

Named Error Bags

Return redirect('register')
            ->withErrors($validator, 'login');
{{ $errors->login->first('email') }}
  • MessageBag.

After Validation Hook

Allows you to attach callbacks to be run after validation is completed.

Llows you to easily perform further validation and even add more error messages to the message collection.

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

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

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

Laravel Validation: Manually Creating Validators — Structure map

Clickable & Draggable!

Laravel Validation: Manually Creating Validators — Related pages: