Laravel parent child relationship, Don't validate self as parent

与世无争的帅哥 提交于 2019-12-25 01:26:24

问题


In Laravel, i have projects table. A project can be sub-project of another project. I keep this parent-child relationship in the same projects table.

When editing a project, the user chooses parent project from a select box. However i want to prevent the user from selecting the same project that is being edited; as a parent project. This would cause loops, thus errors.

How can i achieve this? Best solution i can think of is to write a custom validation rule, however, in that case, how can i get the id attribute to check against project_id field? Or are there better solutions other than validators?

I know i can just exclude that project in select box however it is not proper solution, in case someone tampers post data and modifies the project_id value, (setting it to same value of the project being edited), the infinite loop will happen.

Update: Here is my the code for parent project input generation:

<div class="form-group">
    {{ Form::label('project_id', 'Parent Project:') }}
    {{ Form::select('project_id', [null => null] + Project::lists('name', 'id'), null, ['class' => 'form-control']) }}
</div>

As i stated above, "not including current project id in the select box" is not a proper solution. The application is still vulnerable. It should be prevented in a more proper way.


回答1:


It comes out that the solution is pretty simple, just like in every aspect of Laravel.

It is enough to include

'project_id' => 'different:id',

validation rule in your model. (Ardent syntax)

Here are all validation types with explanations as of Laravel 4.




回答2:


Just retrieve the relationships without the current project.

  $project = Project::find($thisProject);
  $related = Project::where('project_id','=',$project->id)->where('id','!=',$project->id)->get();

And assuming you're using blade...

  <select name="projects">
  @foreach($related as $r)
  <option value="{{$r->id}}">{{$r->projectName}}</option>
  @endforeach
  </select>


来源:https://stackoverflow.com/questions/24396840/laravel-parent-child-relationship-dont-validate-self-as-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!