kuechenplaner's avatar

Pagination with loading relationships is not working

Hello,

how can i paginate the "recipes"? If I use paginate, then it paginates the $user and not the "recipes".


namespace App\Http\Controllers;

use App\Http\Requests\UserProfileRequest;
use App\Models\User;
use Inertia\Inertia;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserProfileController extends Controller
{
    public function show(User $user) {

        $user->load('recipes', "recipes.categories","recipes.ratings", "profile");
       
        return Inertia::render("User/Profile/Show", [
            "user" => $user,
        ]);
    }
}
0 likes
2 replies
LaryAI's avatar
Level 58

To paginate the "recipes" relationship while loading it, you should use the with method combined with paginate on the query builder for the recipes relationship. Here's how you can modify your show method to paginate the recipes:

namespace App\Http\Controllers;

use App\Http\Requests\UserProfileRequest;
use App\Models\User;
use Inertia\Inertia;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserProfileController extends Controller
{
    public function show(User $user, Request $request) {
        // Determine the number of items per page (default to 10)
        $perPage = 10;

        // Load the user's profile
        $user->load('profile');

        // Load and paginate the recipes relationship
        $recipes = $user->recipes()
                        ->with('categories', 'ratings') // eager load related models
                        ->paginate($perPage);

        return Inertia::render("User/Profile/Show", [
            "user" => $user,
            "recipes" => $recipes, // Pass the paginated recipes
        ]);
    }
}

In this solution, we're using the recipes() method to get the query builder for the recipes relationship. We then chain the with method to eager load the categories and ratings relationships for each recipe. Finally, we call paginate to get the paginated result.

The $perPage variable determines how many items you want to display per page. You can adjust this value as needed or even accept it as a request parameter if you want to allow the client to control the pagination size.

By passing the paginated $recipes to the Inertia view, you will now have access to the paginated recipes and can use them in your front-end to display the recipes with pagination controls.

Snapey's avatar

you cannot run paginate on a loaded relationship

load recipes belonging to user in their own right

$recipes = $user->recipes()->with( "recipes.categories","recipes.ratings")->paginate();

Please or to participate in this conversation.