问题
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