Vit Kos
Vit Kos

Reputation: 5755

Laravel pagination with relations

Being new to this framework faced a problem that the resultset is not paginated with the use of standart ->paginate() method if I want to get the result with relations. What is the best approach to achieve the desired ?

Here is my method :

public function findAll($perPage = 15, $order = 'ASC', $orderBy = 'id')
    {
        $users = User::orderBy($orderBy, $order)->with('permissions','companies')->paginate($perPage);
        $users = $users->toArray();
        return $users['data'];

    }

Upvotes: 1

Views: 200

Answers (1)

har2vey
har2vey

Reputation: 676

There's actually no need to convert the result object into array, so in your example you can actually do something like this in the function:

$users = User::orderBy($orderBy, $order)->with('permissions','companies')->paginate($perPage);
return $users;

Then to access the values in your view:

foreach ($users as $user){
    echo $user->name;
}

Upvotes: 1

Related Questions