myJourney
myJourney

Reputation: 43

Push values into an empty array from foreach

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;
}

Upvotes: 1

Views: 449

Answers (2)

AlirezaAhmadi
AlirezaAhmadi

Reputation: 72

I suggest using the namespace first: ‌

use App\Models\User;

For cleaner coding it is better: delete $UserNot and put the relevant code directly in the query:

$verifiedUsers = User::query()
    ->whereNotIn('id', [2,3])
    ->where('role', 'verified')
    ->pluck('id')
    ->toArray();

Upvotes: 1

N69S
N69S

Reputation: 17216

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();

Upvotes: 4

Related Questions