lesssugar
lesssugar

Reputation: 16181

Get a portion of information from Laravel Collection, based on offset and limit

I have problems with getting a specific portion of data from Laravel Collection. In my app, I have the following relation between User and Topic:

User.php model

public function topics() {
        return $this->belongsToMany('Topic', 'stdr_user_topics', 'user_id', 'topic_id')->withTimestamps();
    }

Topic.php model

public function users() {
        return $this->belongsToMany('User', 'stdr_user_topics','topic_id', 'user_id')->withTimestamps();
    }

Based on the ralation I'm trying to get a specific portion of topics that belong to an authenticated user:

if (Auth::check()) {
    // Get topics for authenticated user
    $userTopics = Auth::user()->topics;
    if (count($userTopics)) {
        $result = $userTopics
                    ->where('name', '!=', '')
                     ->sortByDesc('followers')
                     ->skip($offset)
                     ->take($limit);
    } else {
        $result = false;
    }
}

The code above should take the portion of information about user topics, based on $offset and $limit. However, when ran, it throws this:

Call to undefined method Illuminate\Database\Eloquent\Collection::skip()

What is the proper way to achieve what I want for a Collection like above? I'm using Laravel 5.

Upvotes: 0

Views: 1442

Answers (2)

Kun Andrei
Kun Andrei

Reputation: 266

Why don't you used Constraining Eager Loads ?

Maybe you can do something like

Auth::user()->with(['topics' => function($query) use ($limit, $offset) {

    $query->where('name', '!=', '');
    $query->sortByDesc('followers');
    $query->skip($offset);
    $query->take($limit);
}])

Please read here for more info: http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

Good luck!

Upvotes: 1

Maksym
Maksym

Reputation: 3428

Why don't you move this clauses you are using inside of if statement above like:

$userTopics = Auth::user()->topics()->where('name', '!=', '')
                 ->sortByDesc('followers')
                 ->skip($offset)
                 ->take($limit)
                 ->get();
if ($userTopics->count()){
    $result = $userTopics;   
} else {
    $result = false;
}

Upvotes: 2

Related Questions