Home > database >  Push values into an empty array from foreach
Push values into an empty array from foreach

Time:04-14

I have a collection of object retrieved from the database such that the output is [{"id":"5"},{"id":"76"},{"id":"33"}]. I want the output to be: [5, 76, 33].

I tried doing this using the code below but no luck. Working in laravel.

$UserNot = [2,3];
$allverified = array();
$verified = App\Models\User::whereNotIn('id', $UserNot)->select('id')->where('role', 'verified')->get()->take(5);

foreach ($verified as $veribadge) {
    $king = $veribadge->id;
    $allverified[] = $king;
}

CodePudding user response:

You can do it directly from database using pluck without having to initiate a collection of User instances and looping it.

$UserNot = [2,3];
$allverified = App\Models\User::query()
    ->whereNotIn('id', $UserNot)
    ->where('role', 'verified')
    ->pluck('id')
    ->toArray();
  • Related