salep
salep

Reputation: 1380

Laravel Collection to array to string

I have a collection like below and I want to echo out the value.

I found a way to do it (it's a primitive one) but want to learn the Laravel way (so it'll be clean) to use it in my view file using foreach. I used routes.php file since it's not a production version.

Route::get('getall', function() {
    $album= Album::FindOrFail(2)->userImage;
    for($i=0; $i<$album->count(); $i++)
    {
        echo $album[$i]['value'];
    }
});

Upvotes: 0

Views: 1571

Answers (1)

mdamia
mdamia

Reputation: 4557

First check that your query has at least one row or more, it is a good practice to check for results before passing an empty array or object to a loop; To answer your question, you would do something like this:

if (!empty($album)){
    foreach ($album as $key => $value){
        echo $value;
    } 
}else {
    echo '0 found';
}

hope this help.

Upvotes: 1

Related Questions