应用某些条件或验证来限制Laravel模型中的操作

时间:2017-03-02 12:38:09

标签: php laravel-5

enter image description here

这是我在使用Laravel的项目中使用的category表。 我在视图文件中应用了category parent选择下拉列表中的检查,以便category本身及其child's不会出现在下拉列表中。

但是可以使用开发控制台轻松覆盖表单输入字段值。

模型中有没有办法让parent id等于category id本身或parent id是当前child的{​​{1}}那么它会停止执行。

我最近在一个月前开始了laravel,并且仍然在学习和建设,所以在这里的帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我能够通过覆盖模型中的更新方法来解决问题 -

控制器更新方法 -

public function update(Request $request, $id)
        {
            $this->validate($request,
                            ['name' => 'required',]);

            $data = [];

            $data = ['name'   => Input::get('name'),
                     'parent' => !empty(Input::get('parent')) ? Posts_categories::find(Input::get('parent'))->id : NULL,];

            $category = Posts_categories::find($id);

            if(is_null($category))
            {
                Session::flash('flash-message', 'Category type with the given id does not exist.');
                Session::flash('alert-class', 'alert-warning');

                return redirect()->route('admin.post.category.index');
            }

            if($category->update($data)) {
                Session::flash('flash-message', 'Category succesfully updated.');
                Session::flash('alert-class', 'alert-success');
            }

            return redirect()->route('admin.post.category.index');
        }

模型更新方法 -

public function update(array $attributes = [], array $options = [])
        {
            $parent = SELF::find($attributes['parent']);

            if($this->id == $parent->id || $this->id == $parent->parent)
            {
                Session::flash('flash-message', 'Invalid parent selection for category.');
                Session::flash('alert-class', 'alert-warning');
                return 0;
            }

            return parent::update($attributes, $options); // TODO: Change the autogenerated stub
        }
相关问题