2

I have this query :

$inError = DB::table('errors')            
        ->select('fk_fact')
        ->distinct()
        ->get();

And I want it to return an array of integers instead of returning an array of objects, I don't want to loop over all the results and push the values one by one... Is there a way to do this with Laravel?

2 Answers 2

5

Sure, you can use the built-in lists() method:

$inError = DB::table('errors')            
    ->select('fk_fact')
    ->distinct()
    ->lists('fk_fact');

You may need to tack on an ->all() after the lists call.

Here's a tinker example from a database I happened to have up:

>>> DB::table('teams')->select('name')->distinct()->lists('name');
=> [
     "AFC Bournemouth",
     "Arsenal",
     "Aston Villa",
     "Chelsea",
     "Crystal Palace",
     "Everton",
     "Leicester City",
     "Liverpool",
     "Manchester City",
     "Manchester United",
     "Newcastle United",
     "Norwich City",
     "Southampton",
     "Stoke City",
     "Sunderland",
     "Swansea City",
     "Tottenham Hotspur",
     "Watford",
     "West Bromwich Albion",
     "West Ham United",
   ]
Sign up to request clarification or add additional context in comments.

Comments

1

lists was removed in newer versions of the query builder. You can use pluck now.

$inError = DB::table('errors')            
->distinct()
->pluck('fk_fact');

1 Comment

pluck()->toArray() returns a simple array

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.