I have a simple DB record response stored in a variable:
$psr = property_search_request::where('unique_search_id', 'fz62a1zh0a3320zg3712')->first();
Below it I run a foreach loop, like so:
foreach ($psr as $key => $value) {
print_r($key);
}
...If I return $psr, I see the correct output (an array of the record data.)
{
"id": 27,
"created_at": "2021-10-27T16:49:19.000000Z",
"updated_at": "2021-10-27T16:49:19.000000Z",
"unique_search_id": "fz62a1zh0a3320zg3712-65g-6a13",
...
However, when I run the foreach loop I get the below output:
incrementing => 1, exists => 1, wasRecentlyCreated => , timestamps => 1,
How can I loop through a model response in Laravel/PHP,?
CodePudding user response:
What you are seeing as your output (correct output) there is the serialized Model in JSON format. This is getting the Model as an array and then converting that to JSON. So you can just get the Model's attributes (and relationships) as an array with toArray
and iterate that.
foreach ($model->toArray() as $attribute => $value) {
...
}
The incorrect output you are seeing is the default behavior of iterating an object; it will iterate through the public properties.
Laravel 8.x Docs - Eloquent - Serialization - Serializing To Arrays toArray