{"id":9713,"date":"2021-03-19T10:00:36","date_gmt":"2021-03-19T01:00:36","guid":{"rendered":"https:\/\/www.gigas-jp.com\/appnews\/?p=9713"},"modified":"2021-03-18T18:37:30","modified_gmt":"2021-03-18T09:37:30","slug":"tips-to-speed-up-your-database-queries-in-laravel","status":"publish","type":"post","link":"https:\/\/www.gigas-jp.com\/appnews\/archives\/9713","title":{"rendered":"Tips to Speed up your database queries in Laravel"},"content":{"rendered":"\n<p>Here is some tips based on my experience to speed up database queries.<\/p>\n\n\n\n<p><strong>Table Indexing<\/strong><\/p>\n\n\n\n<p>Indexes are important part in database. Indexes are used to\nquickly retrieve data without having to search every row in a database table is\naccessed. The users cannot see the indexes, they are just used to speed up\nsearches\/queries.<\/p>\n\n\n\n<p>How to use? For example, you have thousands of rows of users and you want to get an email.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Select * from users where email = \u201cme@gmail.com\u201d<\/code><\/pre>\n\n\n\n<p>Without index, this process will be from top to bottom until\nit the email is found.<\/p>\n\n\n\n<p> Using with index, in Laravel, the easy way is to create a migration file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function up()\n{\n   Schema::table(\u2018users\u2019, function(Blueprint $table)\n   {\n     $table->index(\u2018email\u2019);\n   });\n}<\/code><\/pre>\n\n\n\n<p>Or if you currently on fresh project just add index to column you want to<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function up()\n{\n    Schema::create(\u2018users, function(Blueprint $table) {\n      \u2026\n      $table->index(\u2018email\u2019);\n      \u2026\n    });\n}<\/code><\/pre>\n\n\n\n<p>Index is not only for single column. You can use multiple column like this&nbsp; <strong>$table-&gt;index([\u2018email\u2019, \u2018 phone_no\u2019]);<\/strong> Let\u2019s us look at a query that could use two different indexes on the table based on the <strong>WHERE <\/strong>clause restrictions. Multi column indexes are called <strong>compound indexes<\/strong>.<\/p>\n\n\n\n<p><strong>Eloquent Eager Loading<\/strong><\/p>\n\n\n\n<p>At its core Eager Loading, is telling Eloquent that you want to grab a model <strong>with <\/strong>specific relationships that way the framework produces a more performant query to grab all the data you will need. By eager loading, you can take many queries down to just one or two. Wrong implementation cause N+1. Here is where common developer do which cause N+1.<\/p>\n\n\n\n<p>For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Class Post extends Model\n{\n  public function author()\n  {\n    return $this->belongsTo(Author::class);\n  }\n}<\/code><\/pre>\n\n\n\n<p>Lets fetch author about 100 rows\nfrom the table and what happen<\/p>\n\n\n\n<p><strong>Mistake 1<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$post = Post::all();\nforeach($posts as $post) \n{\n  $total_user = $post->author;\n}<\/code><\/pre>\n\n\n\n<p>The query runs once to get all the author and for each loop it query another query for author for 100 times. 100 + 1 = N+1 problem. Imagine if you want to fetch thousand to data. If one query cost 100ms * 100 = 10,000ms it takes to complete process.<\/p>\n\n\n\n<p><strong>Solution<\/strong><\/p>\n\n\n\n<p>It can be solve by using with method in Eager loading. For example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$post = App\\Post::with(\u2018author\u2019)->get();<\/code><\/pre>\n\n\n\n<p>If you had multiple related associations, you can eager load them with an array:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$post = App\\Post::with([\u2018author\u2019, \u2018comments\u2019])->get();\n$post =App\\Post::with(\u2018author.profile\u2019)->get();<\/code><\/pre>\n\n\n\n<p>With this, instead of hitting database N+1, with will single query by joining those table and transform it into collection. So you can freely access the collection object without hitting the database. <\/p>\n\n\n\n<p>By Ami<\/p>\n<div class='wp_social_bookmarking_light'>\n            <div class=\"wsbl_google_plus_one\"><g:plusone size=\"medium\" annotation=\"none\" href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/9713\" ><\/g:plusone><\/div>\n            <div class=\"wsbl_hatena_button\"><a href=\"\/\/b.hatena.ne.jp\/entry\/https:\/\/www.gigas-jp.com\/appnews\/archives\/9713\" class=\"hatena-bookmark-button\" data-hatena-bookmark-title=\"Tips to Speed up your database queries in Laravel\" data-hatena-bookmark-layout=\"standard\" title=\"\u3053\u306e\u30a8\u30f3\u30c8\u30ea\u30fc\u3092\u306f\u3066\u306a\u30d6\u30c3\u30af\u30de\u30fc\u30af\u306b\u8ffd\u52a0\"> <img src=\"\/\/b.hatena.ne.jp\/images\/entry-button\/button-only@2x.png\" alt=\"\u3053\u306e\u30a8\u30f3\u30c8\u30ea\u30fc\u3092\u306f\u3066\u306a\u30d6\u30c3\u30af\u30de\u30fc\u30af\u306b\u8ffd\u52a0\" width=\"20\" height=\"20\" style=\"border: none;\" \/><\/a><script type=\"text\/javascript\" src=\"\/\/b.hatena.ne.jp\/js\/bookmark_button.js\" charset=\"utf-8\" async=\"async\"><\/script><\/div>\n            <div class=\"wsbl_twitter\"><a href=\"https:\/\/twitter.com\/share\" class=\"twitter-share-button\" data-url=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/9713\" data-text=\"Tips to Speed up your database queries in Laravel\" data-via=\"GIGASJAPAN_APPS\" data-lang=\"ja\">Tweet<\/a><\/div>\n            <div class=\"wsbl_facebook_like\"><div id=\"fb-root\"><\/div><fb:like href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/9713\" layout=\"button_count\" action=\"like\" width=\"100\" share=\"false\" show_faces=\"false\" ><\/fb:like><\/div>\n            <div class=\"wsbl_facebook_send\"><div id=\"fb-root\"><\/div><fb:send href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/9713\" colorscheme=\"light\" ><\/fb:send><\/div>\n    <\/div>\n<br class='wp_social_bookmarking_light_clear' \/>\n","protected":false},"excerpt":{"rendered":"<p>Here is some tips based on my experience to speed up database queries. Table Indexing Indexes are important pa [&hellip;]<\/p>\n","protected":false},"author":19,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[100],"tags":[],"acf":[],"_links":{"self":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/9713"}],"collection":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/users\/19"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/comments?post=9713"}],"version-history":[{"count":2,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/9713\/revisions"}],"predecessor-version":[{"id":9717,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/9713\/revisions\/9717"}],"wp:attachment":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/media?parent=9713"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/categories?post=9713"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/tags?post=9713"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}