Laravel 5在模型中验证

时间:2016-05-15 15:04:46

标签: php validation laravel laravel-5 laravel-5.2

我有这样的模特

class test extends Model
{

public   $rules = [
    'title' => 'required',
    'name' => 'required',
];
protected $fillable = ['title','name'];
}

像这样的控制器

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());
 }

验证显示错误,如此

  

需要0字段。

我想要展示这个

  

名称字段是必需的。
  标题字段是必需的。

4 个答案:

答案 0 :(得分:6)

我解决了

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());
}

答案 1 :(得分:2)

您还可以查看模型中的验证并抛出ValidationException,该异常将在您的控制器中正常处理(带有错误包等)。例如:

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);
        }
    }

如果模型验证,它将照常继续。如果出现验证错误,则返回上一页,其中包含Flash数据/错误包中的验证错误。

我很可能会将$ person-> validate()方法移到我的服务类中,但是它仍然可以如上所述工作。

答案 2 :(得分:1)

您只需编写Model即可进行验证。

在模型文件中

即Models \ Test.php

public static $createRules = [
   'name'=>'required|max:111',
   'email'=>'required|email|unique:users',
];

在控制器中

public function store(Request $request)
{
     $request->validate(ModalName::$createRules);
     $data = new ModelName();
}

只需执行此操作。一切都会好起来的。

答案 3 :(得分:0)

你这样做是错误的。 rules数组应位于您的控制器中,或更好地位于Form Request

让我告诉你一个更好的方法:

使用php artisan make:request TestRequest创建新的表单请求文件。

示例TestRequest类:

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',
        ];
    }
}

将请求对象注入控制器方法。

public function store(TestRequest $request)
{
    // You don't need any validation, this is already done
    test::create($request->all());
}