Skip to content

Instantly share code, notes, and snippets.

@sydgren
Last active July 11, 2017 20:31
Show Gist options
  • Save sydgren/bb1320f2948bbe0bda025853399dbf71 to your computer and use it in GitHub Desktop.
Save sydgren/bb1320f2948bbe0bda025853399dbf71 to your computer and use it in GitHub Desktop.
Easy handling of optional fields and Laravel validation
<?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);
}
}
<?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