我想为这类问题提供最佳实践
我有items
,categories
和category_item
表,用于多对多关系
我有两个带有这些验证规则的模型
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);
}
}
我不知道如何仅从一个包含类别,标题和内容字段的表单中验证这两组规则。
目前我只对项目进行了验证,但我不知道最好做什么:
这是我的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();
}
}
我对这个主题的一些线索非常感兴趣
感谢
答案 0 :(得分: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();
}
}
另一种方法是创建类似于项目存储库(域)的东西来编排您的项目和类别(模型),并使用验证服务(您也需要创建)以验证您的表单。
Chris Fidao本书,Implementing Laravel,非常好地解释了这一点。
答案 1 :(得分:0)
您也可以使用:
$validationMessages =
array_merge_recursive(
$itemValidation->messages()->toArray(),
$categoryValidation->messages()->toArray());
return Redirect::back()->withErrors($validationMessages)->withInput();
并以同样的方式调用它。
答案 2 :(得分:0)
$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;