AnchovyLegend
AnchovyLegend

Reputation: 12538

Iterating through result set in Laravel controller

I am trying to simply iterate though a result set in laravel on the controller side. This is what I tried but I get the following error:

Cannot use object of type stdClass as array

Controller snippet:

$result = DB::select($query);

foreach($result as $r){
    echo $r['email'];
}

I appreciate any help with this,

Thanks in advance!

Upvotes: 23

Views: 24942

Answers (3)

liviu blidar
liviu blidar

Reputation: 361

The Laravel Collection class supports the standard methods for iterables: map, sort, filter etc. see: vendor/laravel/framework/src/Illuminate/Collections/Collection.php

if you're querying on a model:

$results = MyAwesomeModel::where('something' '=' 'other')->get();

//this is valid
$results->map(function($result) {
  echo $result->field;
});

//this is also valid
for($i = 0; $i < sizeof($results); $i++){
  echo $results[$i]->field;
}

I would suggest avoiding ->toArray() on hydrated results (instances of models) because you loose all the model properties.

Upvotes: 0

Rafiq
Rafiq

Reputation: 11505

After pulling data from database you can convert it to array but it is optional, it's depends on your necessity then you can simply use the foreach to loop through to each distinct object and get access their property

$data = DB:: table('categories')
                ->where('parent_id', $request->value)
                ->get()->toArray();
        $output = '<option value="">Select '.ucfirst($request->dependent).'</option>';
        foreach($data as $row){
            $output.= '<option value="'.$row->id.'">'.$row->title.'</option>';
        }
        return response($output, 200);

Upvotes: 0

Giedrius
Giedrius

Reputation: 633

You need to use it as an object:

$result = DB::select($query);

foreach($result as $r){
    echo $r->email;
}

Or if for some reason you want to use it as array, you need to convert it first:

$result = DB::select($query)->toArray();

foreach($result as $r){
    echo $r['email'];
}

Upvotes: 36

Related Questions