Lakmal Premaratne
Lakmal Premaratne

Reputation: 1229

Laravel convert resultset to array

Database table SITE has many columns. One of them is site_id. I need all the site_ids as an array since it has to be fed to a method which accepts only a string array.

What I tried so far is:

$sites = DB::select('select site_id from site_tab');
$sites_arr = $sites->toArray();

But this doesn't produce the result I want. I need $sites_arr to be like ['A','B','C',...]

Please suggest a way to get this done. A solution based on Eloquent is also OK for me.

Thanks

Upvotes: 0

Views: 1671

Answers (2)

Try this:

DB::table('site_tab')->pluck('site_id')->toArray();

reference pluck

referen toArray

Upvotes: 2

u_mulder
u_mulder

Reputation: 54831

If you open a manual, you will see that

The select method will always return an array of results

So, there's no need to use ->toArray(), as result is already an array.

To get values as array of names you can do:

$site_ids = DB::table('site_tab')->pluck('site_id');

Using ->toArray() here is optional, as you can iterate over $site_ids (which is a Collection) with a foreach too.

Upvotes: 0

Related Questions