laravel验证多个模型

jer*_*lli 4 validation laravel laravel-4

对于这类问题,我想要一个最佳实践

我有items,categoriescategory_item许多关系的表

我有2个带有这些验证规则的模型

class Category extends Basemodel {

    public static $rules = array(
        'name'   => 'required|min:2|max:255'
    );
....


class Item extends BaseModel {

    public static $rules = array(
        'title'   => 'required|min:5|max:255',
        'content' => 'required'
    );
....


class Basemodel extends Eloquent{

    public static function validate($data){
        return Validator::make($data, static::$rules);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何仅从一个包含类别,标题和内容字段的表单中验证这两组规则.

目前我只对项目进行了验证,但我不知道最好做什么:

  • 在我的控制器中创建一组新的规则 - >但它似乎是多余的
  • 顺序验证项目然后类别 - >但我不知道如何处理验证错误,我是否必须合并它们?如何?
  • 我不知道的第三个解决方案

这是我的ItemsController @ store方法

/**
 * Store a newly created item in storage.
 *
 * @return Redirect
 */
public function store()
{
    $validation= Item::validate(Input::all());
    if($validation->passes()){
        $new_recipe = new Item();
        $new_recipe->title    = Input::get('title');
        $new_recipe->content = Input::get('content');
        $new_recipe->creator_id = Auth::user()->id;
        $new_recipe->save();

        return Redirect::route('home')
            ->with('message','your item has been added');
    }
    else{
        return Redirect::route('items.create')->withErrors($validation)->withInput();
    }
}
Run Code Online (Sandbox Code Playgroud)

我对这个问题的一些线索非常感兴趣

谢谢

Ant*_*iro 10

正如您所指出的那样,一种方法是按顺序验证它:

/**
 * Store a newly created item in storage.
 *
 * @return Redirect
 */
public function store()
{
    $itemValidation = Item::validate(Input::all());
    $categoryValidation = Category::validate(Input::all());

    if($itemValidation->passes() and $categoryValidation->passes()){
        $new_recipe = new Item();
        $new_recipe->title    = Input::get('title');
        $new_recipe->content = Input::get('content');
        $new_recipe->creator_id = Auth::user()->id;
        $new_recipe->save();

        return Redirect::route('home')
            ->with('message','your item has been added');
    }
    else{
        return Redirect::route('items.create')
            ->with('errors', array_merge_recursive(
                                    $itemValidation->messages()->toArray(), 
                                    $categoryValidation->messages()->toArray()
                            )
                )
            ->withInput();
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是创建类似于项目存储库(域)的东西来编排项目和类别(模型),并使用验证服务(您也需要创建)来验证表单.

Chris Fidao的书,实施Laravel,非常好地解释了.