0

Controller

$articles = Article::with('tags')->latest()->get();

Blade

@foreach($articles as $article)
    <h2>{{ $article->title }}</h2>
    
    @foreach($article->tags as $tag)
        <span>{{ $tag->name }}</span>
    @endforeach
    
    <hr>
@endforeach

The above works. Now, I'd like to select just some columns from the models.

I have tried the following but now the names of the tags are not displayed and not getting any error.

 $articles = Article::select(['title', 'created_at', 'body', 'slug'])->with(['tags' => function ($query) {
      $query->select('name');
    }])->latest()->get();
Alphy Gacheru
  • 489
  • 1
  • 9
  • 28
  • Does this answer your question? [Laravel Eager Loading - Load only specific columns](https://stackoverflow.com/questions/16994253/laravel-eager-loading-load-only-specific-columns) – miken32 Jun 14 '23 at 18:49
  • See also https://stackoverflow.com/questions/55048919/laravel-nested-eager-loading-and-select or https://stackoverflow.com/questions/50623064/select-specific-fields-in-eloquent-eager-loading-not-working – miken32 Jun 14 '23 at 18:54

1 Answers1

1

Laravel's eager loading system supports loading only some columns.

https://laravel.com/docs/10.x/eloquent-relationships#eager-loading-specific-columns

$articles = Article::select(['id', 'title', 'created_at', 'body', 'slug'])
    ->with('tags:id,name')
    ->latest()
    ->get();

(You'll typically want to ensure you include id, or things get a little wonky.)

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • Getting a blank page after trying it! – Alphy Gacheru Jun 14 '23 at 16:10
  • 1
    Blank pages mean an error of some kind. Check your logs. (And make sure you added your `latest()->get()` to this.) – ceejayoz Jun 14 '23 at 16:22
  • Sorry, I forgot to add that. Still doesn't show the tags only. `$articles = Article::select(['title', 'created_at', 'body', 'slug']) ->with('tags:id,name')>latest()>get();` – Alphy Gacheru Jun 14 '23 at 16:30
  • The following query get's executed `SELECT "tags"."id", "tags"."name", "article_tag"."article_id" AS "pivot_article_id", "article_tag"."tag_id" AS "pivot_tag_id" FROM "tags" INNER JOIN "article_tag" ON "tags"."id" = "article_tag"."tag_id" `WHERE "article_tag"."article_id" in (0)` – Alphy Gacheru Jun 14 '23 at 16:33
  • 1
    You probably want to add `'id'` to your `Article::select` call, in that case. Without it you get the `in (0)` because it doesn't have the article IDs. – ceejayoz Jun 14 '23 at 16:33
  • Adding the `id` fixes the issues, thanks a lot. It's all good now. – Alphy Gacheru Jun 14 '23 at 16:35
  • You know this is a duplicate... – miken32 Jun 14 '23 at 18:49