1

How to I get a specific column value after fetching the results from MySql in Laravel DB select function

Below is my php code.

$list = DB::select('SELECT DISTINCT a.pincode FROM table_name nvs 
        JOIN areas a on nvs.area_id = a.id 
        where nvs.city_id = ?;', [$area_id]);

Below is the results for above query.

[
  {
    "pincode": "560005"
  },
  {
    "pincode": "560006"
  }
]

I need only pincode value not as key value pair. So i tried with the below code.

return array_column($list->toArray(), 'pincode');

It gives Call to a member function toArray() on array.

How can I get only values without using foreach loop.

Answer

I used the below code

$pincode_list = DB::table('table_name as nvs')
            ->join('areas as a', 'nvs.area_id', '=', 'a.id')
            ->select('a.pincode')
            ->where('nvs.city_id', '=', $area_id)
            ->distinct('a.pincode')->pluck('pincode')->toArray();

Result was :

[
    "560067",
    "560035"
]
1
  • 1
    use pluck for single values Commented Jan 3, 2017 at 12:02

4 Answers 4

5

Best way is to use Query Builder or Eloquent and use this instead of get():

->pluck('pincode')->toArray();
Sign up to request clarification or add additional context in comments.

Comments

1

I think the query should be like

 $area_ids = DB::table('table_name')
        ->join('areas', 'nvs.area_id', '=', 'table_name.id')
        ->select('table_name.pincode')
        ->where('nvs.city_id', '=', $area_id)
        ->distinct()->get();

and if you are getting it as object and want it to be array you can use toArray() here like $area_ids = $area_ids->toArray(); can you please test it and let me know the new status.

3 Comments

@Sharath check laravel.com/docs/5.3/queries#joins if you are writing core PHP PDO query why you are usiing Laravel ?
Now i am using laravel functions instead of PDO query
@Sharath if you found my answer helpful, you should have upvoted it .
0
$all_pincodes = array_values ($list);

But I suggest using Laravel Eloquent as you are anyway using Laravel so it's better to use in-build functionalities to ease the process.

Comments

0

Using your variant:

\DB::setFetchMode(\PDO::FETCH_ASSOC);
$data = \DB::select($yourQuery);
$pincodes = array_pluck($data, 'pincode')
\DB::setFetchMode(config('database.fetch')); //return fetch to default

Using more fluent way:

  $pincodes = \DB::table('table')->pluck('pincode')->toArray(); //do not forget about wheres and joins in this query.

I would recommend you second variant because this is more clear way to get result what you need.

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.