i have different input fields and two of them are name_id[] and aussehen[] in the view.for example if user inputs two same value of (1,1) for the name_id and also (1,1) for the aussehen.when i run this query below.
$aussehen=Stufen::whereIN('name_id', $name_id)
->whereIN('stufe',$aussehen)
->get();
I get only one array when dd($aussehen). whereas i wanted to have two same arrays because user inputs the same values two times. But if user select two different values e.g (1,2) for name_id and (3,4) for aussehen then it shows the correct result with two arrays what i am expecting. Now is there anyway to get the same result even if user inputs the same values as much time as he wants?
When you use Model::whereIn('id', [1, 1, 1, 1])->get()
, you tell your SQL database driver to run the query SELECT * from model WHERE id IN (1, 1, 1, 1)
which yields the same results as SELECT * FROM model WHERE id = 1
.
You should know that, besides heavy calculus, the database queries are one of the slowest things in a running PHP application. So you do not want to make multiple queries to the database.
My best guess will be:
$name_id = $request->input('name_id', []);
$aussehen = $request->input('aussehen', []);
$query = Stufen::whereIn('name_id', array_unique($name_id))
->whereIn('stufe', array_unique($aussehen))
->get()
->indexBy('name_id');
$collection = [];
foreach ($name_id as $nameId) {
$collection[] = $results[$nameId];
}
return collect($collection);
What the code does is duplicates (remember, the eloquent models are objects, so it's only the reference) the unique indexed results from the query to a php array returned as a collection afterwards.
To extrapolate a little bit, you should return the $query
directly into your view and use each object as many times as needed, so you will use only the $query
and erase the $collection
part, which is not very nice.