I’m getting confused with the various functions in Laravel’s Eloquent ORM and what they return. I have a Post model for a blog – if I write any of the following then I get back an array of all the posts:
$posts = Post::all();
$posts = Post::get();
$posts = Post::with('user')->all();
However, if I chain some other methods, it doesn’t work. For example this gives an Unhandled Exception error: “Method [all] is not defined on the Query class.”
$posts = Post::with('user')->order_by('updated_at', 'desc')->all();
And if I use the paginate function, I don’t get an array of results at all.
$posts = Post::with('user')->order_by('updated_at', 'desc')->paginate(5);
// index.blade.php
@foreach ($posts as $post)
{{ $post->id }}
@endforeach
I get the error: “Trying to get property of non-object”. Turns out the data is in $posts->results, not $posts.
This is all very confusing! How do I get my head around this? What do each of these functions return and how do I chain them correctly?
Without going through every single method available the simple answer is to figure out what data type the output is.
If it’s an object then find the class that the object is an instance of and understand how that class works.
If it’s a query object, you can chain it, if it’s an array or null you can’t. If it’s an instance of a model class then you CAN chain it, but you can only call methods that exist in the model class or in your derivative class.
Here’s a brief article that I write about Eloquent and Fluent that may be helpful as well: http://laravel.io/topic/17/what-are-fluent-and-eloquent