1

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

2
  • "no luck" is not descriptive enough. What is the issue you're encountering ? is the query even returning any user ids ? or you have an error message ? Commented Apr 13, 2022 at 13:26
  • You are right, will add more detail in the future. Thanks for your help! Commented Apr 13, 2022 at 14:01

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.