Latest

Thursday, July 6, 2017

Laravel, first() vs loop

Asked by: user7432810


I have an object on which I can run first() but I don't know how to loop through it.

$types = $biz->types()->first();
echo $types->name; //works great and gives me the name

This works fine but if I try:

    $types = $biz->types(); //returns a BelongsToMany object
    foreach($types as $type){
        echo $type->name; //doesn't enter the loop at all
    }

Edit: the following wouldn't work:

 $biz->types; //returns an empty collection

This one doesn't give me anything and loop wouldn't initiate.

My question: How do I loop through $types and not just the first one?

PS: I wanted to focus on the loop and first so I didn't bring all the details.



Source

No comments:

Post a Comment

Adbox