I have below Models and I need to get an array of district_id
without field name. (like, [1, 2, 3, 4]
)
Province [id, description]
District [id, description, province_id]
$province_arr = DB::table('provinces')->pluck('id')->toArray();
$district_arr = DB::table('districts')->pluck('id')
->whereIn('province_id', $province_arr)->toArray();
But $district_arr
is always empty. (i.e. dd($district_arr)
always give []
)
Database contains data to match the query. Can someone help me figure out why doesn't this work?
You should use pluck
AFTER whereIn
like so:
$district_arr = DB::table('districts')->whereIn('province_id', $province_arr)
->pluck('id')->toArray();
because pluck
is here the method that gets data from database. If you add condition after getting from database you are not getting what you expected.
Otherwise you get data from database and then you run whereIn
on Support Collection and there are no records with province_id
because all of them have only id
as you specified in pluck