Eliya Cohen
Eliya Cohen

Reputation: 11458

Using Laravel's pluck method without an associative array

Let's say I've got an Articles collection, and I want to fetch the popular articles.

So first, I make a scopePopular() method in the Article method. Very simple.

Now I want to fetch their ids, so I'll do this:

Article::popular->pluck('id');

The result will be an associative array:

[
    0 => 1,
    1 => 34,
    2 => 17
    ...
];

I want to get a normal array, without the keys, Like:

[1, 34, 17]

I know I can just do something like this:

array_values(Article::popular->pluck('id'));

But I believe Laravel has much more cleaner way to do this. Any ideas?

Upvotes: 0

Views: 6854

Answers (4)

mujuonly
mujuonly

Reputation: 11861

$store_type = \App\Websites::find($request->store_id)->first()->store_type;

// Outputs - just a string like "live" // there was option like a demo, live, staging ...

It might be useful for someone else.

Upvotes: 0

DevK
DevK

Reputation: 9942

All arrays have indexes.

[
    0 => 1,
    1 => 34,
    2 => 17
];

equals to

[1, 34, 17]

In other words:

$a1 = [0 => 1, 1 => 34, 2 => 17];
$a2 = [1, 34, 17];
$a1 === $a2;
// returns True

Upvotes: 8

Ayush Ghosh
Ayush Ghosh

Reputation: 487

Its exactly what you need and what you get, By default php has the incremental key from 0.

You want to see something like a JSON array I assume. Just do a return the array and you will see the JSOn array in browser, but internally its like this only.

Please confirm and let me know.Thanks

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You can use values() method which is wrapper for array_values():

Article::popular->pluck('id')->values();

Upvotes: 1

Related Questions