你们还可以看看看你的模式是否正确,并 throw弃一种 Val笑,在你的控制人(有错误的袋子等)将照常处理。 例如:
abstract class BaseModel extends Model implements ModelInterface {
protected $validationRules = [];
/**
* Validate model against rules
* @param array $rules optional array of validation rules. If not passed will validate against object s current values
* @throws ValidationException if validation fails. Used for displaying errors in view
*/
public function validate($rules=[]) {
if (empty($rules))
$rules = $this->toArray();
$validator = Validator::make($rules,$this->validationRules);
if ($validator->fails())
throw new ValidationException($validator);
}
/**
* Attempt to validate input, if successful fill this object
* @param array $inputArray associative array of values for this object to validate against and fill this object
* @throws ValidationException if validation fails. Used for displaying errors in view
*/
public function validateAndFill($inputArray) {
// must validate input before injecting into model
$this->validate($inputArray);
$this->fill($inputArray);
}
}
然后,在我的主计长中:
public function store(Request $request) {
$person = $this->personService->create($request->input());
return redirect()->route( people.index , $person)->with( status , $person->first_name. has been saved );
}
最后,我的基本服务班级
abstract class BaseResourceService {
protected $dataService;
protected $modelClassName;
/**
* Create a resource
* @param array $inputArray of key value pairs of this object to create
* @returns $object
*/
public function create($inputArray) {
try {
$arr = $inputArray;
$object = new $this->modelClassName();
$object->validateAndFill($arr);
$this->dataService->create($object);
return $object;
}
catch (Exception $exception) {
$this->handleError($exception);
}
}
If the model validates it continues as usual. If there s a validation error it goes back to the previous page with the validation errors in the flash data/error bag.
我很可能将“人”和“有效”方法移至我的服务类别,但如上所述,这种方法仍将有效。