phplaravelapi

how to manipulate controller's return data with pagination


In my Laravel application I'm using a controller to fetch database for a specific model that's called "Questions" which has a user_id foreign key indicating the creator user

my index() function looks like this:

public function index()
    {
        return Question::orderBy('id', 'desc')->cursorPaginate(10);
    }

here I'm paginating results using cursor pagination-

at the current state this returns an object containing a data property in which questions are stored.

I need to add to those questions a property containing the creator user's profile picture link that is stored inside the User Model by the profile_image_url property.

in a few words what I'm trying to do is including some user data inside the questions themselves not to make any more requests to get creator user's data


Solution

  • You should join users table with questions table to fetch related user info.

    Try this sql query:

    public function index()
    {
        return Question::query()
            ->select('questions.*' , 'users.profile_image_url')
            ->join('users' , 'users.id' , 'questions.user_id')
            ->orderBy('id', 'desc')
            ->cursorPaginate(10);
    }