Laravel 验证多个模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19120672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:30:21  来源:igfitidea点击:

laravel validate multiple models

validationlaravellaravel-4

提问by jeremy castelli

I would like a best practice for this kind of problem

我想要这种问题的最佳实践

I have items, categoriesand category_itemtable for a many to many relationship

我有itemscategoriescategory_item多对多关系的表

I have 2 models with these validations rules

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

I don't know how to validate these 2 sets of rules from only one form with category, title and content fields.

我不知道如何仅从一个带有类别、标题和内容字段的表单中验证这两组规则。

For the moment I just have a validation for the item but I don't know what's the best to do:

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

  • create a new set of rules in my controller -> but it seems redundant
  • sequentially validate Item then category -> but I don't know how to handle validations errors, do I have to merges them? and how?
  • a 3rd solution I'm unaware of
  • 在我的控制器中创建一组新规则 -> 但它似乎是多余的
  • 依次验证项目然后类别 -> 但我不知道如何处理验证错误,我是否必须合并它们?如何?
  • 我不知道的第三个解决方案

here is my ItemsController@store method

这是我的 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();
    }
}

I am very interested on some clue about this subject

我对这个主题的一些线索很感兴趣

thanks

谢谢

回答by Antonio Carlos Ribeiro

One way, as you pointed yourself, is to validate it sequentially:

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

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

The other way would be to create something like an Item Repository (domain) to orchestrate your items and categories (models) and use a Validation Service (that you'll need to create too) to validate your forms.

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

Chris Fidaobook, Implementing Laravel, explains that wonderfully.

Chris Fidao 的书《实现 Laravel》很好地解释了这一点。

回答by user3779015

You can also use this:

你也可以使用这个:

$validationMessages = 
    array_merge_recursive(
        $itemValidation->messages()->toArray(), 
        $categoryValidation->messages()->toArray());

return Redirect::back()->withErrors($validationMessages)->withInput();

and call it in the same way.

并以相同的方式调用它。

回答by Christopher Kikoti

$validateUser = Validator::make(Input::all(), User::$rules);
$validateRole = Validator::make(Input::all(), Role::$rules);

if ($validateUser->fails() OR $validateRole->fails()) :
    $validationMessages = array_merge_recursive($validateUser->messages()->toArray(), $validateRole->messages()->toArray());

    return Redirect::back()->withErrors($validationMessages)->withInput();

endif;