2

I am just very new to laravel and today I have run some code and get stuck at this code.

    $topic = topic::where('id', $id)->get();
    if(is_array($topic)){
        echo 'yes';
    }
    else{
        echo 'no';
    }

The result is 'no' but I can "foreach" loop through each topic.

As I unserstand, 'Foreach' accepts only array parameter but if it's a real array why is_array return "no"?

1
  • You are incorrect about foreach. Anything that is Traversable can be iterated over with foreach (as well as arrays) Commented May 9, 2016 at 18:04

3 Answers 3

3

Because it's not an array. It's a collection.

You can convert it to an array with toArray() method:

$topic = topic::where('id', $id)->get()->toArray();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks!. So I can loop through collection because laravel make it can?(laravel core make collections serve as iterators)
Kind of. But not Laravel, PHP does it. php.net/manual/en/language.oop5.iterations.php
0

I want to Add something

In the end you will loop through weather it is an array or collection.

$topic = topic::where('id', $id)->get()->toArray();

So why you need to cast it toArray, it'll just take extra execution time to return result as an array the rather you can do same thing with collection.

Comments

0

It's also worth mentioning that dealing with collections can be really painless, thanks to a lot of available methods. Check the link form official documentation.

Then you can check against empty collection, like isEmpty(), etc. Try to use as much as Laravel gives you out of the box.

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.