Home / Snippets / How To Select Specific Columns in Laravel 8 Eloquent
How To Select Specific Columns in Laravel 8 Eloquent cover

How To Select Specific Columns in Laravel 8 Eloquent

796

3 years ago

0 comments

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".
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this