Posts Learn Components Snippets Categories Tags Tools new About
/

How To Select Specific Columns in Laravel 8 Eloquent

Learn how to optimize your query by only selecting some of the specific columns in Laravel 8

Created on Jun 26, 2021

293 views

One of the ways to optimize the retrieval speed of your data is to only select the columns from your database. To achieve that, you can specify to retrieve only the column that you want to use. You can make use of the "select" method or "get" method to accomplish this.

Imagine you have the following columns in your "Article" model. If you have 15000 articles and you are getting it by using the "all" method, then highly likely the system will take time to load your data.
  • id
  • title
  • body
  • image
  • links
  • created_at
  • updated_at

So instead of querying using "all" method like below.

Before
$articles = Article::all();

foreach($articles as $article) {
    dd($article);
}

You can instead specify the only column that's necessary.

After
$articles = Article::select('id, 'title', 'image')->get();

// or

$articles = Article::get(['id', 'title', 'image']);

By doing so, the query speed will be much faster and your computer/server can save ton of memory.

Do note that the code above is only for an example, if you have those many records then it's better to "paginate" or load it in "chunks".

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)