Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Laravel, which Eloquent methods return data and which return objects?

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?

like image 879
DisgruntledGoat Avatar asked Oct 21 '25 12:10

DisgruntledGoat


2 Answers

Without going through every single method available the simple answer is to figure out what data type the output is.

dd($whatever);

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

like image 132
Shawn McCool Avatar answered Oct 24 '25 02:10

Shawn McCool


When I run this:

$user = User::where('email','=','[email protected]');
dd($user); # object(Illuminate\Database\Eloquent\Builder)

// After: 
dd($user->get()); # object(Illuminate\Database\Eloquent\Collection)

// And finally, to get model object:
dd($user->get()->first()); # object(App\User)
like image 32
М.Б. Avatar answered Oct 24 '25 02:10

М.Б.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!