{"id":11203,"date":"2021-12-16T10:00:00","date_gmt":"2021-12-16T01:00:00","guid":{"rendered":"https:\/\/www.gigas-jp.com\/appnews\/?p=11203"},"modified":"2021-12-15T19:31:00","modified_gmt":"2021-12-15T10:31:00","slug":"tips-best-practices-for-laravel-8","status":"publish","type":"post","link":"https:\/\/www.gigas-jp.com\/appnews\/archives\/11203","title":{"rendered":"Tips &amp; best practices for Laravel 8"},"content":{"rendered":"\n<p>This article will show you the mysterious tricks that might help you when writing code with Laravel.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><strong>1<em>.Use local scopes when you need to query things<\/em><\/strong><\/p>\n\n\n\n<p>Laravel has a nice way to write queries for your database driver using Query Builder. Something like this:<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p>$orders = Order::where(&#8216;status&#8217;, &#8216;delivered&#8217;)-&gt;where(&#8216;paid&#8217;, true)-&gt;get();<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p>This is pretty nice.But this bit of code can be better written if we use local scopes.<\/p>\n\n\n\n<p id=\"b599\">Local scopes allow us to create our Query Builder methods we can chain when we try to retrieve data. For example, instead of&nbsp;<code>-&gt;where()<\/code>&nbsp;statements, we can use&nbsp;<code>-&gt;delivered()<\/code>&nbsp;and&nbsp;<code>-&gt;paid()<\/code>&nbsp;in a cleaner way.<\/p>\n\n\n\n<p id=\"c4c9\">First, in our&nbsp;<code>Order<\/code>&nbsp;model, we should add some methods:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class Order extends Model<br>{<br>   ...<br>   public function scopeDelivered($query) {<br>      return $query-&gt;where('status', 'delivered');<br>   }   public function scopePaid($query) {<br>      return $query-&gt;where('paid', true);<br>   }<br>}<\/pre>\n\n\n\n<p>When declaring local scopes, you should use the&nbsp;<code>scope[Something]<\/code>&nbsp;exact naming. In this way, Laravel will know that this is a scope and will make use of it in your Query Builder. Make sure you include the first argument that is automatically injected by Laravel and is the query builder instance.<\/p>\n\n\n\n<p>$orders = Order::delivered()-&gt;paid()-&gt;get();<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p>For more dynamic retrieval, you can use dynamic local scopes. Each scope allows you to give parameters.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class Order extends Model<br>{<br>   ...<br>   public function scopeStatus($query, string $status) {<br>      return $query-&gt;where('status', $status);<br>   }<br>}$orders = Order::status('delivered')-&gt;paid()-&gt;get();<\/pre>\n\n\n\n<p>Laravel uses by default&nbsp;<code>where[Something]<\/code>&nbsp;to replace the previous scope. So instead of the previous one, you can do:<\/p>\n\n\n\n<p>Order::whereStatus(&#8216;delivered&#8217;)-&gt;paid()-&gt;get();<\/p>\n\n\n\n<p>Laravel will search for the&nbsp;<code>snake_case<\/code>&nbsp;version of&nbsp;<code>Something<\/code>&nbsp;from&nbsp;<code>where[Something]<\/code>. If you have&nbsp;<code>status<\/code>&nbsp;in your DB, you will use the previous example. If you have&nbsp;<code>shipping_status<\/code>, you can use:<\/p>\n\n\n\n<p>Order::whereShippingStatus(&#8216;delivered&#8217;)-&gt;paid()-&gt;get();<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><strong><em>2.Magic scopes<\/em><\/strong><\/p>\n\n\n\n<p id=\"123b\">When building things, you can use the magic scopes that are already embedded<\/p>\n\n\n\n<ul><li>Retrieve the results by&nbsp;<code>created_at<\/code>&nbsp;, descending:<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\">           User::latest()-&gt;get();<\/pre>\n\n\n\n<ul><li>Retrieve the results by any field, descending:<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\">           User::latest('last_login_at')-&gt;get();<\/pre>\n\n\n\n<ul><li>Retrieve results in random order:<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\">           User::inRandomOrder()-&gt;get();<\/pre>\n\n\n\n<ul><li>Run a query method only if something\u2019s true:<\/li><\/ul>\n\n\n\n<p><\/p>\n\n\n\n<p><strong><em>3.Do not store model-related static data in configs<\/em><\/strong><\/p>\n\n\n\n<p id=\"90fd\">Instead of this:<\/p>\n\n\n\n<p id=\"7216\"><code>BettingOdds.php<\/code><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class BettingOdds extends Model\n{\n   ...\n}\n\nconfig\/bettingOdds.php\n\nreturn [\n   'sports' =&gt; [\n      'soccer' =&gt; 'sport:1',\n      'tennis' =&gt; 'sport:2',\n      'basketball' =&gt; 'sport:3',\n      ...\n   ],\n];<\/pre>\n\n\n\n<p>And accessing them using:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">config(\u2019bettingOdds.sports.soccer\u2019);<\/pre>\n\n\n\n<p id=\"1e0d\">I prefer doing this:<\/p>\n\n\n\n<p id=\"692f\"><code>BettingOdds.php<\/code><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class BettingOdds extends Model<br>{<br>   protected static $sports = [<br>      'soccer' =&gt; 'sport:1',<br>      'tennis' =&gt; 'sport:2',<br>      'basketball' =&gt; 'sport:3',<br>      ...<br>   ];<br>}<\/pre>\n\n\n\n<p id=\"4a85\">And access them using:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">BettingOdds::$sports['soccer'];<\/pre>\n\n\n\n<p>Because it\u2019s easier to be used in further operations:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class BettingOdds extends Model<br>{<br>   protected static $sports = [<br>      'soccer' =&gt; 'sport:1',<br>      'tennis' =&gt; 'sport:2',<br>      'basketball' =&gt; 'sport:3',<br>      ...<br>   ];public function scopeSport($query, string $sport)<br>   {<br>      if (! isset(self::$sports[$sport])) {<br>         return $query;<br>      }<br>      <br>      return $query-&gt;where('sport_id', self::$sports[$sport]);<br>   }<br>}<\/pre>\n\n\n\n<p id=\"5ce0\">Now we can enjoy scopes:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">BettingOdds::sport('soccer')-&gt;get();\n<\/pre>\n\n\n\n<p><strong><em>4.Use collections instead of raw-array processing<\/em><\/strong><\/p>\n\n\n\n<p>Back in the days, we were used to working with arrays in a raw way:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">$fruits = ['apple', 'pear', 'banana', 'strawberry'];foreach ($fruits as $fruit) {<br>   echo 'I have '. $fruit;<br>}<\/pre>\n\n\n\n<p>Now, we can use advanced methods that will help us process the data within arrays. We can filter, transform, iterate and modify data inside an array:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">$fruits = collect($fruits);$fruits = $fruits-&gt;reject(function ($fruit) {<br>   return $fruit === 'apple';<br>})-&gt;toArray();['pear', 'banana', 'strawberry']<\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p>Tsuki<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><\/pre>\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\/11203\" ><\/g:plusone><\/div>\n            <div class=\"wsbl_hatena_button\"><a href=\"\/\/b.hatena.ne.jp\/entry\/https:\/\/www.gigas-jp.com\/appnews\/archives\/11203\" class=\"hatena-bookmark-button\" data-hatena-bookmark-title=\"Tips &amp; best practices for Laravel 8\" 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\/11203\" data-text=\"Tips &amp; best practices for Laravel 8\" 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\/11203\" 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\/11203\" colorscheme=\"light\" ><\/fb:send><\/div>\n    <\/div>\n<br class='wp_social_bookmarking_light_clear' \/>\n","protected":false},"excerpt":{"rendered":"<p>This article will show you the mysterious tricks that might help you when writing code with Laravel. 1.Use loc [&hellip;]<\/p>\n","protected":false},"author":21,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[35],"tags":[],"acf":[],"_links":{"self":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/11203"}],"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\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/comments?post=11203"}],"version-history":[{"count":2,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/11203\/revisions"}],"predecessor-version":[{"id":11227,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/11203\/revisions\/11227"}],"wp:attachment":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/media?parent=11203"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/categories?post=11203"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/tags?post=11203"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}