BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::toArray()'

22,287

Solution 1

If you want to actually "get" relational data, you don't put parenthesis arount tags. This will work just fine:

$article->tags->toArray();

You put parenthesis when you need to "query" to that collection (Ex. sync, save, attach).

Reference: https://laravel.com/docs/5.1/eloquent-relationships#many-to-many

Solution 2

I had the same problem and solved it by adding get()

For example:

$article->tags()->get()->toArray();
Share:
22,287
Hashmatullah Noorzai
Author by

Hashmatullah Noorzai

As long as you tried your best, you don't worry about the rest! My love Afghanistan, my home USA... Alhamdulillah <3

Updated on July 09, 2022

Comments

  • Hashmatullah Noorzai
    Hashmatullah Noorzai over 1 year

    I am working along with @Jeffrey_way series of Laracasts Many to Many Relations (With Tags)

    Below is the code I have written in CMD using Laravel Tinker:

    After executing the last line of code ($article->tags()->toArray();

    Although everything seems to be OK with my code but still I get following error:

    BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::toArray()'
    
  • Hashmatullah Noorzai
    Hashmatullah Noorzai over 7 years
    now I get this error: BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::all()'
  • delatbabel
    delatbabel over 7 years
    Depending on your version of Laravel, all() may return either a collection or an array. If it returns an array then you don't need the ->toArray() bit at all.
  • Hashmatullah Noorzai
    Hashmatullah Noorzai over 7 years
    Thank you Yigit I was adding parentheses from my own dumb head :p although it wasn't in the training video