laraveleloquent-relationship

How to use >select(fields list and relation in 1 eloquent request?


On laravel 10 site making request from Post table(which has a lot of columns I got also related creator table :

        $postList = Post
            ::orderBy('created_at', 'desc')
            ->with('creator')
            ->get();

and I have access to

$post->creator->name

field. I try to reduce number requested fields with fields list :

        $postList = Post
            ::orderBy('created_at', 'desc')
            ->with('creator')
            ->select('id', 'title', 'slug', 'published', 'created_at')

But in this case I see error as $post->creator is null

and in sql - tracement I see fields listed

   SELECT `id`, `title`, `slug`, `published`, `created_at`
    FROM `post`
    ORDER BY `created_at` desc

If there is a way to use >select(fields list and relation in 1 request ?

"laravel/framework": "^10.48.4",

Thanks in advance!


Solution

  • When you're explicitly defining columns on your queries and loading relationships you have always to make sure that the keys whose those relationships depend are also defined. E.g.:

            $postList = Post::select(
                    'id',
                    'creator_id', // fk to Creator model
                    'title',
                    'slug',
                    'published',
                    'created_at',
                )
                ->with('creator:id,name,other_columns...') // now related creators can be matched
                ->latest()
                ->get();