0

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?

Amit
  • 5,924
  • 7
  • 46
  • 94
Eliya Cohen
  • 10,716
  • 13
  • 59
  • 116
  • 1
    There is no such thing in php. All arrays have their indexes. There is literally no difference between [0=>1, 1=>34] and [1, 34]. – DevK Jan 10 '17 at 12:36

4 Answers4

8

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
DevK
  • 9,597
  • 2
  • 26
  • 48
  • 1
    You're right. the issue I had was because of my bad approach to the structure of the array. Thanks for clarifying it :) – Eliya Cohen Jan 10 '17 at 12:45
1

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

Article::popular->pluck('id')->values();
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • Please don't add the same answer to multiple questions. Answer the best one and flag the rest as duplicates. See http://meta.stackexchange.com/questions/104227/is-it-acceptable-to-add-a-duplicate-answer-to-several-questions – Bhargav Rao Jan 10 '17 at 12:41
0

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

Ayush Ghosh
  • 487
  • 2
  • 10
0
$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.

mujuonly
  • 11,370
  • 5
  • 45
  • 75