Custom Validation With The Same Workflow In Laravel (V5.2+)

- the good thing about this is u can have any extra validation logic in here like the “After Validation Hook” and you still get the same flexibility as before

** still don’t know how to use only “StoreValidation $v” without the “Request $request” so we can use “$v->all()

  • controllers/PostController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Validations\Post\StoreValidation;

class PostController extends Controller
{
  public function store(Request $request, $id, StoreValidation $v)
  {
    // if validation failed, it will automaticlly redirect back
    // https://laravel.com/docs/5.2/validation#form-request-validation
    // https://laravel.com/docs/5.3/validation#form-request-validation

    // $request->all()
  }
}
  • validations\Post\StoreValidation
namespace App\Http\Validations\Post;

use Validator;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Validation\ValidatesRequests;

class StoreValidation
{

  use ValidatesRequests;


  public function __construct(Request $request)
  {
    if ( ! $this->authorize()) {
      abort(403);
    }

    $this->validate($request);
  }


  protected function authorize()
  {
    return true;
  }


  protected function validate($request)
  {
    $rules = [
      // ...
    ];

    // validation factory
    $validator = Validator::make($request->all(), $rules);

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

    // fire an exception and redirect on fail
    if ($validator->fails()) {
      $this->throwValidationException($request, $validator);
    }
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s