DanielRønfeldt's avatar

Retrieve only certain attributes of the model instead of all

Hey guys, silly question.

This should be a trivial subject, but I simply can't recall what approach to take here.

Out of an Eloquent Collection of, say, $project models, I need to pass to my View only certain attributes of each model, instead of sending over all attributes of each model.

$projects = Project::with('category')->latest()->get();
foreach($projects as $project) {
  echo "<pre>";
  var_export($project);
  echo "</pre>";
}

which of course, gives me a list of projects, each with all attributes, e.g.

array (
  'id' => 1,
  'category_id' => 1,
  'title' => 'Title of the first project',
  'slug' => 'title-of-the-first-project',
  'description' => 'Quo et aut recusandae...',
  'client' => 'Maecenas ticidunt',
  'featured_photo' => 1,
  'created_at' => '2023-04-10 20:44:43',
  'updated_at' => '2023-04-26 08:30:52',
),

But my View doesn't care about the description, client, featured_photo, created_at, nor updated_at attributes.

It needs just the id, category_id, title, and slug attributes of each model, nothing more.

Retrieving such a big amount of extra, redundant data, is slowing down the server's response time. Which I obviously indend to avoid.

How can this be achieved, the Laravel way?

Thanks!

0 likes
4 replies
Snapey's avatar

with ->select('id','category_id', 'title', 'slug')

You can also pass as an array into get()

$projects = Project::with('category')->latest()->get(['id','category_id', 'title', 'slug']);

1 like
javierroman's avatar

As you have used the with() method to load the category relationship, it will retrieve all columns from the categories table. If you want to select only specific columns from the categories table, you can use the select() method inside the with() method,:

$projects = Project::with(['category' => function ($query) { $query->select('id', 'name'); }])->latest()->get(['id', 'category_id', 'title', 'slug']);

1 like
cwhite's avatar

@javierroman

You can also just use a simple string:

$projects = Project::query()
    ->select(['id', 'category_id', 'title', 'slug'])
    ->with(['category:id,name'])
    ->latest()
    ->get();
3 likes

Please or to participate in this conversation.