Last active
July 11, 2017 20:31
-
-
Save sydgren/bb1320f2948bbe0bda025853399dbf71 to your computer and use it in GitHub Desktop.
Easy handling of optional fields and Laravel validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SomeController extends Controller | |
{ | |
public function someMethod(Request $request) | |
{ | |
$data = $request->intersect(array_keys(SomeModel::$rules)); | |
$validator = validator($data, SomeModel::$rules; | |
if ($validator->fails()) { | |
throw new ValidationException($validator); | |
} | |
// $data is now validated and only consists of the fields that were actually provided. | |
// In case 'baz' wasn't provided, it won't be set as an empty string in the database. | |
return SomeModel::create($data); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SomeModel extends Model | |
{ | |
public static $rules = [ | |
'foo' => 'required|in:a,b,c', | |
'bar' => 'required|numeric', | |
'baz' => 'email', | |
'bob' => 'required|date', | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment