I am working on a Laravel project, which should be somewhat modular.
I have written a search query and what I want is following:
Models:
Assessment A
Assessment B
Assessment C
View:
{{ Form::open(array('route' => 'search')) }}
<select multiple name="search_by_form[]">
<option selected>Any</option>
<option value="assessment_a">A</option>
<option value="assessment_b">B</option>
<option value="assessment_c">C</option>
</select>
{{ Form::close() }}
Controller:
The controller is much more complex but I made it easier for you to understand what my need is.
Now something like follows:
$user_entry =$request->input('search_by_form', []);
$resultArray = [];
foreach ($user_entry as $entry){
if ($entry == "assessment_a"){
$model_results = AssessmentA::where("approved",1)->get();
} elseif ($entry == "assessment_b"){
$model_results = AssessmentB::where("approved",1)->get();
} elseif($entry == "assessment_c"){
$model_results = AssessmentC::where("approved",1)->get();
}
}
What I want:
SearchViewController: foreach through Models in specific folder
then:
{{ Form::open(array('route' => 'search')) }}
<select multiple name="search_by_form[]">
<option selected>Any</option>
@foreach($models as $model)
<option value="{{ $model }}">{{ $model->name }}</option>
@endforeach
</select>
{{ Form::close() }}
Instead of having such an ugly approach is it possible to have more something like this:
foreach ($user_entry as $entry){
$entry::where("approved",1)->get(); #Obviously the values on the view would be change to "AssessmentA", etc.
}
I this feasible?
Thank in advance!
CodePudding user response:
I think you will create any array like this:
$model_array = ['assessment_a' => AssessmentA::class];
Then in loop simply pass value
foreach ($user_entry as $entry){
$model_array[$entry]::where("approved",1)->get(); #Obviously the values on the view would be change to "AssessmentA", etc.
}
CodePudding user response:
If you change the select values to the actual table names, you could do it easily
{{ Form::open(array('route' => 'search')) }}
<select multiple name="search_by_form[]">
<option selected>Any</option>
<option value="assessments_a">A</option>
<option value="assessments_b">B</option>
<option value="assessments_c">C</option>
</select>
{{ Form::close() }}
$user_entry = $request->input('search_by_form', []);
if (empty($user_entry)) {
model_results = collect();
} else {
$query = DB::table(array_shift($user_entry))->where('approved', 1);
foreach ($user_entry as $table) {
$query->union(fn($union) => $union->from($table)->where('approved', 1));
}
$model_results = $query->get();
}
