-
-
Notifications
You must be signed in to change notification settings - Fork 176
Conditional Validation Example
Pe Ell edited this page Jul 10, 2017
·
4 revisions
This is a basic example of how to use conditional validations.
PostController.php
<?php
namespace App\Http\Controllers;
use JsValidator;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Define your validation rules in a property in
* the controller to reuse the rules.
*/
protected $validationRules = [
'email' => 'required|email',
'games' => 'required|numeric',
];
/**
* Show the edit form for blog post.
* We create a JsValidator instance based on shared validation rules.
*
* @param string|int $post_id
* @return \Illuminate\Http\Response
*/
public function edit($post_id)
{
$jsValidator = JsValidator::make($this->validationRules);
$jsValidator->sometimes('reason', 'required|max:500');
$post = Post::find($post_id);
return view('edit_post')->with([
'validator' => $jsValidator,
'post' => $post,
]);
}
/**
* Store the incoming blog post.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validation = Validator::make($request->all(), $this->validationRules]);
$validation->sometimes('reason', 'required|max:500', function ($input) {
return $input->games >= 100;
});
if ($validation->fails()) {
return redirect()->back()->withErrors($validation->errors());
}
// do store stuff
}
}
To enable conditional validations, in the controller you need to specify the attribute and rules to validate conditionally. This rules will be validated using Ajax
$jsValidator->sometimes('reason', 'required|max:500');