Reputation: 1763
Eloquent ORM in Laravel 4.2 drives me crazy. I want to retrieve the recent added records a user has.
I have 3 models: User, Folder, File. A User has many folders and a folder has many files. Also a User has many files through folders (I think I don't need to post my models source here, I hope my description is accurate enough).
$files = Auth::User() -> files;
return $files;
This code shows me all files a user has.
$files = Auth::User() -> files() -> orderBy('updated_at', 'DESC') -> take(5) -> get();
return $files;
This code is actually doing what I want. Giving back the last 5 records which have been edited. But I want to mak this reusable and extend my model with a function. And this is where I fail:
# File.php (model):
public function recentFiles()
{
return $this -> orderBy('updated_at', 'DESC') -> take(5) -> get();
}
# Controller:
$files = Auth::User() -> files -> recentFiles;
return $files;
This ends in a "undefined property: $recentFiles" error. What is my problem?
Thanks
Upvotes: 0
Views: 35
Reputation: 172
You can achieve that using the Query Scopes.
# File.php (model)
public function scopeRecentFiles($query)
{
return $query->orderBy('updated_at', 'DESC')->take(5);
}
# Controller
$files = Auth::User()->files()->recentFiles()->get();
return $files;
Upvotes: 2