Laravel 5 validation in model
I solve it
public function store(Request $request)
{
$test=new test; /// create model object
$validator = Validator::make($request->all(),$test->rules);
if ($validator->fails()) {
return view('test')->withErrors($validator)
}
test::create($request->all());
}
You are doing it the wrong way. The rules
array should either be in your controller or better in a Form Request.
Let me show you a better approach:
Create a new Form Request file with php artisan make:request TestRequest
.
Example TestRequest
class:
namespace App\Http\Requests;
use App\Http\Requests\Request;
class TestRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation messages.
*
* @return array
*/
public function messages()
{
return [
'title.required' => 'A title is required.',
'name.required' => 'The name field is required'
];
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required',
'name' => 'required',
];
}
}
Inject the request object into your controller method.
public function store(TestRequest $request)
{
// You don't need any validation, this is already done
test::create($request->all());
}
You could also look at validating in your model and throwing a ValidationException which will be handled as usual in your controller (with the error bag etc). E.g:
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);
}
}
Then in my Controller:
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');
}
Finally in my base service class
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.
I will most probably move the $person->validate() method to my service class, however it will still work as outlined above.