【发布时间】:2015-03-12 06:08:27
【问题描述】:
想问一下为什么下面的代码可以正常工作,重定向正常,数据插入成功:
类别控制器:
public function store()
{
$data = Input::all();
$category = new Term;
if($category->saveCategory($data)){
return Redirect::route('admin_posts_categories')->withSuccess('Category successfully added.');
}else{
return Redirect::route('admin_posts_categories')->withError('Failed to add category. #ErrorCode : 13');
}
}
术语模型:
public function saveCategory($data){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
$category_taxo = new TermTaxonomy;
$category_taxo->term_id = $this->lastCategoryId();
$category_taxo->taxonomy = 'category';
$category_taxo->description = $data['description'];
if($category_taxo->save()){
return true;
}else{
return false;
}
}else{
return "#Error Code : 4";
}
}
如下仅插入数据但随后显示空白页面且不重定向:
类别控制器:
public function store()
{
$data = Input::all();
$category = new Term;
$category->saveCategory($data);
}
术语模型
public function saveCategory($data){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
$category_taxo = new TermTaxonomy;
$category_taxo->term_id = $this->lastCategoryId();
$category_taxo->taxonomy = 'category';
$category_taxo->description = $data['description'];
if($category_taxo->save()){
return redirect::route('admin_posts_categories')->withSuccess('Category successfully added.');
}else{
return redirect::route('admin_posts_categories')->withError('Failed to add category.');
}
}else{
return redirect::route('admin_posts_categories')->withError('#Error Code : 4.');
}
}
此外,我想问一些相关的问题,我的代码是否符合正确的设计模式,我应该将重定向放在哪里,在模型中还是在控制器中?
【问题讨论】:
-
您绝对不应该将重定向逻辑放入您的模型中。如果你想学习更好的 Laravel 技术,我建议你访问 laracasts.com
-
请不要将
inline code formatting用于跨越多行的代码块,因为在这些情况下它们会变得非常难看。改用 4 空格缩进的代码块,例如选择您的代码并单击编辑器工具栏中的{}图标。
标签: laravel laravel-4 laravel-routing