<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jeff Madsen on Medium]]></title>
        <description><![CDATA[Stories by Jeff Madsen on Medium]]></description>
        <link>https://medium.com/@codebyjeff?source=rss-a4df2ac24cb9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qxyDKRjraYJY9L7T.jpg</url>
            <title>Stories by Jeff Madsen on Medium</title>
            <link>https://medium.com/@codebyjeff?source=rss-a4df2ac24cb9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:53:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codebyjeff/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SUBQUERY to find waiting period after multiple occurances]]></title>
            <link>https://medium.com/@codebyjeff/subquery-to-find-waiting-period-after-multiple-occurances-3875a6bca3e8?source=rss-a4df2ac24cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3875a6bca3e8</guid>
            <dc:creator><![CDATA[Jeff Madsen]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 04:21:21 GMT</pubDate>
            <atom:updated>2022-01-04T09:03:20.765Z</atom:updated>
            <content:encoded><![CDATA[<h3>SUBQUERY to find waiting period after multiple occurrences</h3><p>Oh, dear! What a title! Let me explain the situation up front, so you can see what this is about (and understand why it was so hard to pick a catchy title for it).</p><p>In our example, we are managing a db for a test center. A user (customer) is allowed to take a specific test up to three times, after which he must wait 6 months to try that test again. This query result (a count) is passed back to the main application where the business logic is applied.</p><p>(Another useful purpose for this query might be, “Find all of the customers who have ordered more than X times with us, but now have not ordered anything for the last Y months”).</p><p>First, let’s make a sample table with some data:</p><p>(I’m going to keep this very simple, and hard-code values in my query so it is easier to understand. You may need to change the dates of the test_submissions; they should all be WITHIN 180 DAYS of Now() )</p><pre>-- Table structure for table `test_submission` -- <br>CREATE TABLE IF NOT EXISTS `test_submission` <br>( `id` int( 11 ) NOT NULL AUTO_INCREMENT ,<br> `test_id` int( 11 ) DEFAULT NULL ,<br> `user_id` int( 11 ) DEFAULT NULL ,<br> `result` varchar( 10 ) DEFAULT NULL ,<br> `ctime` datetime DEFAULT NULL ,<br> PRIMARY KEY ( `id` ) <br>); </pre><pre>INSERT INTO `test`.`test_submission` (`id` ,`test_id` ,`user_id` ,`result` ,`ctime`) <br>VALUES <br>(NULL , &#39;1&#39;, &#39;1&#39;, &#39;rejected&#39;, &#39;2013-08-09 10:23:10&#39;), <br>(NULL , &#39;1&#39;, &#39;1&#39;, &#39;rejected&#39;, &#39;2013-08-15 10:43:41&#39;), <br>(NULL , &#39;1&#39;, &#39;1&#39;, &#39;rejected&#39;, &#39;2013-08-30 10:23:10&#39;);</pre><p>a test submission row is created each time a test is taken. So, let’s find out if this user can take the test again today.</p><p>Now, the logic to this is a little “inside-out”, and so I hope I can explain it clearly. Let us start with our subquery, since this is where we are really restricting our rows:</p><pre>SELECT DATE_ADD(MAX(TS2.ctime), INTERVAL -180 DAY) <br>FROM test_submission TS2 <br>WHERE TS2.user_id = 1 <br>AND TS2.test_id = 1 <br>AND TS2.result = &#39;rejected&#39; <br>AND NOW() &lt; DATE_ADD(TS2.ctime, INTERVAL 180 DAY);</pre><p>We need to find out, Has there been a rejection within the last 180 days?</p><p>“NOW() &lt; DATE_ADD(TS2.ctime, INTERVAL 180 DAY)” let’s us look at only those rows; “DATE_ADD(MAX(TS2.ctime), INTERVAL -180 DAY)” will then get a date 180 days earlier than the most recent of that subset. That’s our starting point.</p><p>Now, from that return date (‘2013–03–03 10:23:10’ in this example), let’s work forward again to find out, How many rejections have there been after that (i.e., within 180 days of the most recent failure)?</p><pre>That&#39;s confusing. Let me try to summarize once more: We want to see if there has been a rejection within the waiting period of 180 days. So we look at all the rejections, and take the most recent. Now, just because he has a rejection within 180 days of today doesn&#39;t mean he&#39;s disqualified from taking the test again - we need to check that rejection to see if it is the 3rd in a 180 day period (because he only has to wait 180 days after his 3rd rejection). If it IS his 3rd failure, we already know he hasn&#39;t waited long enough. I just messed you up even more, didn&#39;t I?</pre><p>To simplify the explanation, I’ll just plug in the date from above for now:</p><pre>SELECT count(TS.id) as count <br>FROM test_submission TS <br>WHERE TS.user_id = 1 <br>AND TS.test_id = 1 <br>AND TS.result = &#39;rejected&#39; <br>AND TS.ctime &gt; (&#39;2013-03-03 10:23:10&#39;);</pre><p>The answer here is 3. For my own application logic, I’ve chosen to return the actual count. You could put a HAVING count(TS.id) &gt; 3 and worked off a true/false, or whatever suits you.</p><p>3! Nope, he can’t take it today — needs more study time.</p><p>Here is the final query, all in one piece:</p><pre>SELECT count(TS.id) as count <br>FROM test_submission TS <br>WHERE TS.user_id = 1 <br>AND TS.test_id = 1 <br>AND TS.result = &#39;rejected&#39; <br>AND TS.ctime &gt; (<br>     SELECT DATE_ADD(MAX(TS2.ctime), INTERVAL -180 DAY)    <br>     FROM test_submission TS2 <br>     WHERE TS2.user_id = 1 <br>     AND TS2.test_id = 1 <br>     AND TS2.result = &#39;rejected&#39; <br>     AND NOW() &lt; DATE_ADD(TS2.ctime, INTERVAL 180 DAY)<br>);</pre><p>Hope that helped!</p><pre>Jeff Madsen is a web applications programmer living in Japan. Follow him on<a href="https://twitter.com/codebyjeff">Twitter</a> if that&#39;s your thing, or drop him a line about an interesting project.</pre><p><em>Originally published at </em><a href="https://oldblog.codebyjeff.com/blog/2013/09/subquery-to-find-waiting-period-after-multiple-occurances"><em>https://oldblog.codebyjeff.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3875a6bca3e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ENUM and ORDER BY FIELD — customized sorting in mysql]]></title>
            <link>https://medium.com/@codebyjeff/enum-and-order-by-field-customized-sorting-in-mysql-326c2e8638e1?source=rss-a4df2ac24cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/326c2e8638e1</guid>
            <dc:creator><![CDATA[Jeff Madsen]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 04:20:41 GMT</pubDate>
            <atom:updated>2021-12-20T04:20:41.311Z</atom:updated>
            <content:encoded><![CDATA[<h3>ENUM and ORDER BY FIELD — customized sorting in mysql</h3><p>“…and we’d like the jobs sorted by Started, Pending, Finished, please.”</p><p>How many times have you heard that and cringed? Didn’t marketing people learn the alphabet when they were young?</p><p>Well, throw away those awful CASE WHEN… hacks and subquery tables. Make way for ENUM and ORDER BY FIELD!</p><p>The fastest way to deal with a customized sort is by using ENUM. ENUM will sort your column in the order you list the possible values. For example,</p><pre>-- Table structure for table `fieldSort` CREATE TABLE IF NOT EXISTS `fieldsort` ( `id` int(11) NOT NULL AUTO_INCREMENT, `column` enum(&#39;start&#39;,&#39;pending&#39;,&#39;finished&#39;) NOT NULL, PRIMARY KEY (`id`) ); -- Dumping data for table `fieldSort` INSERT INTO `fieldSort` (`id`, `column`) VALUES (1, &#39;pending&#39;), (2, &#39;start&#39;), (3, &#39;start&#39;), (4, &#39;finished&#39;), (5, &#39;pending&#39;), (6, &#39;finished&#39;);</pre><p>Now run:</p><pre>SELECT * FROM `fieldSort` ORDER BY `column`</pre><p>Magic!</p><p>But, suppose you cannot use ENUM on this field for some reason, or you need to do further manipulations? ORDER BY FIELD to the rescue!</p><p>Here is that same table, without the ENUM:</p><pre>CREATE TABLE IF NOT EXISTS `fieldsort` ( `id` int(11) NOT NULL AUTO_INCREMENT, `column` varchar(25) NOT NULL, PRIMARY KEY (`id`) );</pre><p>Now try:</p><pre>SELECT * FROM `fieldSort` ORDER BY FIELD (`column` , &#39;start&#39;, &#39;pending&#39;, &#39;finished&#39;);</pre><p>Voila! as the Belgians say.</p><p>But what happens if you don’t include all of the possible values in your list?</p><p>Add INSERT INTO `test`.`fieldSort` (`id` ,`column`) VALUES (NULL , ‘approved’); and we’ll see…</p><p>The values not in the list show first, in the order they were entered in the table, then the values you asked to order. You can see this more clearly by leaving out ‘start’ and ‘approved’ both:</p><pre>SELECT * FROM `fieldSort` ORDER BY FIELD (`column` , &#39;pending&#39;, &#39;finished&#39;)</pre><p>So why use ORDER BY FIELD? While it’s true that ENUM is faster, and you will need to have a good list of your values to make this really work out, I think you will find plenty of occasions where an ENUM was not used and you’ll be happy to have this as a solid backup in your bag of tricks.</p><p>Hope that was helpful!</p><p><em>Originally published at </em><a href="https://oldblog.codebyjeff.com/blog/2013/11/enum-and-order-by-field-customized-sorting-in-mysql"><em>https://oldblog.codebyjeff.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=326c2e8638e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sql puzzle: Returning Customers]]></title>
            <link>https://medium.com/@codebyjeff/sql-puzzle-returning-customers-60300e56b7bd?source=rss-a4df2ac24cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/60300e56b7bd</guid>
            <dc:creator><![CDATA[Jeff Madsen]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 04:20:05 GMT</pubDate>
            <atom:updated>2021-12-20T04:20:05.456Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s the end of the month, and your store manager comes to you with a request. The store ran a special promotion in the third week of September with the idea of luring back existing customers who hadn’t shopped in a while. He has all the sales data for the month, but he can’t tell which customers had slipped and only came back during the promotion period. He asks for your help.</p><p>“We ran the promotion from Sept 22–28. I’d like to know — which customers came in sometime during the first two weeks of the month, didn’t come in at all during the third week, but returned during our promo period.”</p><p>Let’s throw together some data and see how to solve this sort of problem. We’ll use the month of Sept 2013, say that the promo period was the 22–28th. The “pause” is the 15th-21st; an existing customer is one who came in BEFORE the 15th, but NOT during the “pause”.</p><pre>CREATE TABLE `visits` ( `id` int(11) NOT NULL AUTO_INCREMENT, `customer_id` int(11) NOT NULL, `visit_date` date NOT NULL, PRIMARY KEY (`id`) ) ; INSERT INTO `visits` (`id`, `customer_id`, `visit_date`) VALUES (1, 1, &#39;2013-09-03&#39;), (2, 1, &#39;2013-09-11&#39;), (3, 1, &#39;2013-09-25&#39;), (4, 2, &#39;2013-09-10&#39;), (5, 2, &#39;2013-09-18&#39;), (6, 2, &#39;2013-09-25&#39;), (7, 3, &#39;2013-09-26&#39;);</pre><p>Our first inclination to solve this is probably to try to come up with some sort of WHERE clause that looks for a customer_id where the visit_date is BETWEEN Sept 22 and 28 AND NOT BETWEEN Sept 15 AND 21 AND is less than Sept 15. Well, obviously that can’t work for a single record, so we want to somehow GROUP BY customer_id and then apply the filters. But how do we apply 3 different filters to the same group of records simultaneously?</p><p>HAVING might jump to mind, but HAVING only works on the grouped result rows, not within the group. The rule of thumb for WHERE vs. HAVING is:</p><p>- first WHERE filters out rows<br> — then GROUP BY aggregates them<br> — then HAVING filters the aggregated rows</p><p>So we need a different solution. Three filters means three queries, roughly speaking. UNIONS? Get the previous cutomers, UNION to the last week return customers, subtract out any who came in during the pause…No, not going to work out.</p><p>Let’s back up a moment. We want our customer to be in two different time periods… two different result sets…When we have two different sets of data, how do we find out what the matching data is? With a JOIN, of course! This is just like finding the customer_id that exists in two different tables.</p><p>Now we’re making progress! Let’s look at a simple query for the return week and the pre-pause times:</p><pre>SELECT DISTINCT v.customer_id FROM `visits` v WHERE v.`visit_date` BETWEEN &#39;2013-09-22&#39; AND &#39;2013-09-28&#39;; SELECT DISTINCT v.customer_id FROM `visits` v WHERE v.`visit_date` &lt; &#39;2013-09-15&#39;;</pre><p>Okay, so we could wrap those both in table aliases and join them, but we are still left with how to ignore the results that also came in during the pause. So we need something like this pseudo code:</p><pre>// NOT REAL CODE! SELECT customer_id FROM (SELECT DISTINCT v.customer_id FROM `visits` v, WHERE v.`visit_date` BETWEEN &#39;2013-09-22&#39; AND &#39;2013-09-28&#39;) as returnWeek JOIN (SELECT DISTINCT v.customer_id FROM `visits` v WHERE v.`visit_date` &lt; &#39;2013-09-15&#39;) as previousCustomer ON (previousCustomer.customer_id = returnWeek.customer_id) WHERE customer_id NOT IN (SELECT v.customer_id FROM `visits` v, WHERE v.`visit_date` BETWEEN &#39;2013-09-15&#39; AND &#39;2013-09-22&#39;)</pre><p>I suppose that would probably work, but I don’t really see it scaling well (and I’m personally not a big fan of NOT IN when it can be helped). However, we are on the right track. If we could just get rid of that NOT IN clause…</p><p>What if we think of our second query as a table of ALL rows before the return week (ie, before Sept 22) and then filtered that to get our subset that excludes the pause? This would mean that inside this “table”, a customer could have many visits, but the latest one must be BEFORE Sept 15. Something like:</p><pre>SELECT `customer_id` FROM `visits` WHERE `visit_date` &lt; &#39;2013-09-22&#39; GROUP BY `customer_id` HAVING MAX(`visit_date`) &lt; DATE_ADD(&#39;2013-09-22&#39;, INTERVAL -7 DAY);</pre><p>We’ve done it! This will now exclude all the “pause week” customers, so we can just join this to our first query to see who is included in both:</p><pre>SELECT DISTINCT v.customer_id FROM `visits` v JOIN (	SELECT `customer_id` FROM `visits` WHERE `visit_date` &lt; &#39;2013-09-22&#39; GROUP BY `customer_id` HAVING MAX(`visit_date`) &lt; DATE_ADD(&#39;2013-09-22&#39;,INTERVAL -7 DAY)) as PreviousData ON (PreviousData.customer_id = v.customer_id) WHERE v.`visit_date` BETWEEN &#39;2013-09-22&#39; AND &#39;2013-09-28&#39;;</pre><p>There you have it! Took some thinking, but we got there.</p><p>Final Words: While the solution was fun to track down, in the end it may not work for us. Our tables may be too big, or our servers too small, or other issues may crop up. The point of doing exercises like this is not to simply memorize a bunch of solutions to apply in certain cases, but to teach ourselves how to think about how the data is stored and formed and queried, so when we come across something complex we know what to try.</p><p>Hope that helped!</p><pre>Jeff Madsen is a web applications programmer living in Japan. Follow him on<a href="https://twitter.com/codebyjeff">Twitter</a> if that&#39;s your thing, or drop him a line about an interesting project.</pre><p><em>Originally published at </em><a href="https://oldblog.codebyjeff.com/blog/2013/09/sql-puzzle-returning-customers"><em>https://oldblog.codebyjeff.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60300e56b7bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[codebyjeff — Single Table Inheritence in Laravel: No more If’s]]></title>
            <link>https://medium.com/@codebyjeff/codebyjeff-single-table-inheritence-in-laravel-no-more-ifs-12c4e17e3794?source=rss-a4df2ac24cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/12c4e17e3794</guid>
            <dc:creator><![CDATA[Jeff Madsen]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 04:18:17 GMT</pubDate>
            <atom:updated>2022-08-26T03:05:23.616Z</atom:updated>
            <content:encoded><![CDATA[<h3>Single Table Inheritence in Laravel: No more If’s</h3><p>Recently I watched Misko Hevery’s talk <a href="https://www.youtube.com/watch?v=4F72VULWFvc">“The Clean Code Talks — Inheritance, Polymorphism, &amp; Testing”</a> and was particulary struck by his polymorphism example. It matched what I had wanted to do on more than one occasion, but had always been in a hurry to “just get it done” and had never taken the time to setup.</p><p>We’ve all had that horrible <em>switch()</em> code where we loop over a result set and route the row into a different action or behavior based on some values in the row, such as the record status. <em>Doing it wrong!</em> is what “they” always say. But how do we do it right?</p><p>Enter “Single Table Inheritence”</p><p>The code I’m going to show you is similar Mark Smith’s <a href="http://www.colorfultyping.com/single-table-inheritance-in-laravel-4/">http://www.colorfultyping.com/single-table-inheritance-in-laravel-4/</a>, which I’d recommend as a slightly different take on the solution, but hopefully this article will help explain it a in way that will help you understand the basic idea more clearly.</p><p>Here is what we are trying to achieve: We would like to cycle through the result set, and for each “row” return a different object that matches specifically the needs of that row, based on some criteria in the record (such as status). In many frameworks the result row that is returned is a simple array, but in Laravel an instance of the model is returned. This actually makes things much easier for us because all we need to do is swap out the default return object with our own.</p><p>Backing up a little bit, let’s look inside the Laravel Illuminate\Database\Eloquent\Model.php to see what’s going on. The function we are most interested in is <em>newFromBuilder($attributes = array())</em>. This is where the return object is created. If you call for a single row, such as using Post::find(1), this is called once. If you are getting a result set with more than one row, you are actually just creating a Collection object which in turn calls this many times, one for each row, and creates an array of objects (models). So this is where we’d like to break in and override it with our own class.</p><p>First, time for a bit of code. A simple table and some really terrible sample data.</p><pre>CREATE TABLE `posts` ( <br>`id` int(10) unsigned NOT NULL AUTO_INCREMENT, <br>`title` varchar(200) NOT NULL, <br>`body` text NOT NULL, <br>`status` varchar(20) NOT NULL DEFAULT &#39;unread&#39;, <br>PRIMARY KEY (`id`) ) <br>ENGINE=InnoDB DEFAULT CHARSET=utf8; </pre><pre>INSERT INTO `posts` (`id`, `title`, `body`, `status`) <br>VALUES (1, &#39;Wow this is great&#39;, &#39;Most amazing thing ever&#39;, &#39;unread&#39;), <br>(2, &#39;This is read&#39;, &#39;I read this&#39;, &#39;read&#39;);</pre><p>Also, a couple of simple models. Post is our main model, but we’ll also make empty PostRead and PostUnread.</p><pre>class Post extends Eloquent { } </pre><pre>class PostRead extends Post { } </pre><pre>class PostUnread extends Post { }</pre><p>In the vein of keeping things simple, we’ll just use our routes file instead of a controller and view. I’m going to put the <em>bad</em> code we don’t like in below, and we can refactor it.</p><pre>Route::get(&#39;/&#39;, function() { <br>     $collection = \Post::all(); </pre><pre>     $new = $collection-&gt;map(function($post) { <br>          switch($post-&gt;status) { <br>               case &#39;read&#39;: <br>                    return &#39;For post title: &#39;.$post-&gt;title . &#39; we would do a read action&#39;; <br>                    break; <br>               case &#39;unread&#39;: <br>               default: return &#39;For post title: &#39;.$post-&gt;title . &#39; we would do an unread action&#39;; <br>                    break; <br>          } <br>     }); </pre><pre>     var_dump($new); <br>});</pre><p>All we are doing is appending a string to the title, based on the status. In real life, we might want to build a out the html differently, or do some internal work, or just about anything. That’s precisely where the problem lies — what if we want to do ALL those things? Then we would need to have switch statements all over our code, with each one perhaps doing a different job — or the same code duplicated. The typical solution to this has been to make a helper class and pass each row into it. But what if we could make each row already know how it is supposed to behave, through polymorphism?</p><p>Head back the newFromBuilder() function on Model.php</p><pre>public function newFromBuilder($attributes = array()) { <br>     $instance = $this-&gt;newInstance(array(), true);       </pre><pre>     $instance-&gt;setRawAttributes((array) $attributes, true);<br> <br>     return $instance; <br>}</pre><p>This is where Laravel builds the instance of the model for each row. newInstance() — called directly above this — does the actual work of creating the instance which we then apply the attributes. If you put a var_dump($attributes) in this function, you’ll see a stdClass object with each of the fields we are requesting, which just gets “snapped onto” the Post model instance. So this is where we want to do our work. We want to intercept this creation of a new Post model instance and instead create an instance of our inherited class (ie, PostRead or PostUnread).</p><pre>// Post.php // override the base Model function public function</pre><pre>newFromBuilder($attributes = array()) { <br>     $class = &#39;Post&#39;. ucwords($attributes-&gt;status); <br>     $instance = new $class; $instance-&gt;exists = true;<br>     $instance-&gt;setRawAttributes((array) $attributes, true);<br>     return $instance; <br>}</pre><p>That’s very quick and sloppy (you’ll need to handle a default instance, for example, for when the class is not found), but you can see what we are doing — we read the row’s status field, and instead of creating a Post instance, we make either a PostRead or PostUnread instance.</p><p>So now we are in position to use polymorphism. Recall the earlier code where we used a switch to dynamically change the title string. Instead of that, we will have each class change the string according to its own rule. So change our models to be:</p><pre>class Post extends Eloquent { <br>     <br>     function change_title() { <br>          return &#39; we would do nothing&#39;; <br>     } <br>} </pre><pre>class PostRead extends Post { <br>     function change_title() { <br>          return &#39; we would do a read action&#39;; <br>     } <br>} </pre><pre>class PostUnread extends Post { <br>     function change_title() { <br>          return &#39; we would do an unread action&#39;; <br>     } <br>}</pre><p>Change our main controller code (in the route for this example) to:</p><pre>$new = $collection-&gt;map(function($post) { <br>     return &#39;For post title: &#39;.$post-&gt;title . $post-&gt;change_title(); });</pre><p>Now each row will return either an instance of PostRead or PostUnread, and logic specific to either of those statuses can be added and fired off where needed. It gives us both the advantage of more easily testable classes and nice packages for each bit of business logic.</p><p>How might you use this? Technically, anywhere there is a switch statement of complicated if conditions (I agree with Misko that replacing every single if clause is a bit over-doing it). One place I’m considering is in the case of dynamic forms, where each row represents a question for a survey or form, which might be a text field, dropdown, checkbox, etc. Taking all that messy out of your presenter or view, and wrap it in a class of its own. I’m sure you can thing of cases in your projects.</p><p>Hope that helped! Definitely take some time to watch Misko’s presentation to understand why we are doing this.</p><p><em>Originally published at </em><a href="https://oldblog.codebyjeff.com/blog/2014/07/single-table-inheritence-in-laravel"><em>https://oldblog.codebyjeff.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12c4e17e3794" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[codebyjeff — Laravel Quick Tip: orderByRaw() with ORDER BY FIELD]]></title>
            <link>https://medium.com/@codebyjeff/codebyjeff-laravel-quick-tip-orderbyraw-with-order-by-field-20f9fb334e3f?source=rss-a4df2ac24cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/20f9fb334e3f</guid>
            <dc:creator><![CDATA[Jeff Madsen]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 04:17:40 GMT</pubDate>
            <atom:updated>2021-12-20T04:17:40.561Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel Quick Tip: orderByRaw() with ORDER BY FIELD</h3><p>Just a quick tip that really extends an old post from here about MySQL’s ORDER BY FIELD ( <a href="https://oldblog.codebyjeff.com/blog/2013/11/enum-and-order-by-field-customized-sorting-in-mysql">ENUM and ORDER BY FIELD — customized sorting in mysql</a>)</p><p>Building an API and we want to allow users to request items and have them returned <em>in the same order they ask for them</em>. In other words, if they request items/?id=2,7,3,1 the response should come back ordered by id’s 2,7,3,1</p><p>The solution is quite simple (once I remembered my own old trick for this) — we collect the id’s string and <em>explode()</em> them to make a <em>whereIn()</em> clause, then use that same string in our ORDER BY FIELD. So the query we are after looks like:</p><pre>SELECT id, morestuff FROM items WHERE id IN (2,7,3,1) ORDER BY FIELD (id, 2,7,3,1);</pre><p>The “quick tip” is how to get the order by to work with Laravel. The usual function is -&gt;orderBy(‘field’, ‘ASC|DESC’), but that won’t work for us because if you use ASC or DESC, it overrides your FIELD and won’t sort as you like. However, the function expects a second parameter and will add a default ASC if you leave it out.</p><p>Fortunately, Taylor was nice enough to always make sure developers can get in there and write their own code when they need to. While the Laravel.com’s site doesn’t list everything, the API docs have a lot of hidden gems. If you look at the <a href="http://laravel.com/api/4.2/">API docs</a> and drill down to Illuminate\Database\Query\Builder you see that each of the main clauses of your CRUD statements have an underlying <em>raw()</em> version where you can write your own code. The one we wanted was orderByRaw(). Here’s the whole thing in all it’s glory (a bit modified from my actual code, which is not something I can simply copy/paste for you):</p><pre>// $input[&#39;id&#39;] is a string = &quot;2,7,3,1&quot; // $ids is an array of that string $ids = $this-&gt;urlHelper-&gt;explode_ids($input[&#39;id&#39;]); // NOTICE! id in the FIELD function should NOT have quotes - this is mysql. After the field, we // list ids, again no array as this is raw sql. $this-&gt;repo-&gt;whereIn($ids)-&gt;orderByRaw(\DB::raw(&quot;FIELD(id, &quot;.$input[&#39;id&#39;].&quot; )&quot;))-&gt;get();</pre><p>That’s all there is to it! I probably don’t even need that \DB::raw() wrapper, but I like to use it whenever I’m adding my own sql this way, so call it habit. A good lesson in why you should try to get as familiar with the API Docs as you can.</p><p>Hope that helped!</p><p><em>Originally published at </em><a href="https://oldblog.codebyjeff.com/blog/2015/02/laravel-quick-tip-order-by-raw"><em>https://oldblog.codebyjeff.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20f9fb334e3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[codebyjeff — Eloquent Create, Update, New…the Untold Story]]></title>
            <link>https://medium.com/@codebyjeff/codebyjeff-eloquent-create-update-new-the-untold-story-96751ac0e1c3?source=rss-a4df2ac24cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/96751ac0e1c3</guid>
            <dc:creator><![CDATA[Jeff Madsen]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 04:15:45 GMT</pubDate>
            <atom:updated>2021-12-20T04:15:45.765Z</atom:updated>
            <content:encoded><![CDATA[<h3>Eloquent Create, Update, New…the Untold Story</h3><p>Tag: Laravel 5.1+, Eloquent</p><p>Like zombies, they lurch forward out of the swirling fog of the documentation, threatening your peace of mind…`firstOrNew`. `firstOrCreate`. `updateOrCreate`. You can look away, but you can never forget they’re there…</p><p>Okay, probably better saved for Halloween than April Fool’s. Still, for a great many of us, it captures the feeling, doesn’t it? We <em>know</em> they must be for something, and the fact that we don’t know for <em>what</em> leaves us slightly unsettled. Over on <a href="http://codebyjeff.com/newsletter">Laravel Quick Tips</a> we’ve been looking at a few of these functions and their uses, and I thought it might be helpful to collect all of them together in a single (I hope) coherent post.</p><p>Without further preamble, let’s get to it. I’m going to use the basic User object and table that ships with a default installation of Laravel so you can follow along if you like.</p><p><strong>New vs. Create</strong></p><p>Let’s start by answering one of the fundamental differences in creating new records — what is the difference between using these two bits of code?</p><pre>User::create([&#39;name&#39; =&gt; &#39;Jeff&#39;]); $user = new User([&#39;name&#39; =&gt; &#39;Joe&#39;]); $user-&gt;save();</pre><p>The answer is a simple one — `create` actually creates and saves the <em>record</em>; the second method creates a new User <em>instance</em> but does not fire the save() method. Don’t believe me? Have a look at Illuminate\Database\Eloquent\Model::create. It looks exactly like the second example!</p><p>Why would we do that? Why take the extra steps if we have a nice wrapper function? Because we are using an ORM. Something I see that is very common, and I think a mistake, is to ignore the fact that you are using an ORM and instead set up your relationships manually.</p><p>For example:</p><pre>new Post::create([&#39;user_id&#39; =&gt; 1, &#39;title&#39; =&gt; &#39;The title&#39;]);</pre><p>This is bad for a couple of reasons. First — isn’t that the job of the ORM? Of course it is! Compare:</p><pre>$post = Post::create([&#39;title&#39; =&gt; &#39;The title&#39;]); User::find(1)-&gt;posts()-&gt;save($post);</pre><p>Not only do I let my ORM do the work, but it gives me added security of checking that I’ve got the right User and they exist. (Better still is to write this with findOrFail, for example).</p><p>BUT!! I have a problem, which ties us back in to my original point. If you have set up your foreign keys correctly, this second method will fail! Why? Because you are tying to `create` the Post without the user_id, which will be required. That’s why we simply make a new instance without saving it.</p><pre>$post = new Post([&#39;title&#39; =&gt; &#39;The title&#39;]); User::find(1)-&gt;posts()-&gt;save($post);</pre><p>In this case, Laravel will add the `user_id` itself, based on your relationship info. There are a few ways of making a new instance without saving (using factories, for example, which we’ll touch on when we look into testing more), but this is the most straightforward.</p><p><strong>findOrNew, firstOrCreate, updateOrCreate, …</strong></p><p>Once you understand the logic above, it’s all downhill. There are a whole host of functions that are essentially two-step wrappers, with the name clearly saying what it does. The first action can be `first`, `find` or `update`, coupled with either `new` or `create`, as your situation calls for. Let’s check how those three prefixes differ.</p><p><em>findOrNew (no findOrCreate)</em></p><p>A simple extension of `find`, this will search for the primary key or else create a new model instance. Here’s a little tip: `find()` has a second parameter where you can pass an array of fields you want returned, instead of selecting all of them.</p><p>There is no `findOrCreate` — my assumption is, we want the primary key to be created via the usual auto-increment on the table. You can get around this by using `firstOrCreate`.</p><p><em>firstOrNew/firstOrCreate</em></p><p>These functions allow you to check if a record already exists and only create it if it doesn’t. You may not have realized, but you can also pass a subset of fields to check against using:</p><pre>User::firstOrCreate([&#39;name&#39; =&gt; &#39;Jeff&#39;, &#39;email&#39; =&gt; &#39;jeff@codebyjeff.com&#39;]);</pre><p>where the full array will be used as a where clause, and if no record is found, it will be created.</p><p><em>updateOrCreate (no updateOrNew)</em></p><p>Here is an edge case, but I run into it rather frequently when I want to make new records based on a template. The `firstOrCreate` is very handy to search for or create a record, but the problem is that it will only make it <em>with that exact of data</em>. So if your data also had ‘some_count’ =&gt; 12 that wasn’t actually part of the <em>search</em>, you can’t do it with the insert.</p><p>Fear not! This is what the surprisingly undocumented updateOrCreate() is for:</p><pre>Illuminate\Database\Eloquent\Model::updateOrCreate(array $attributes, array $values = [])</pre><p>The first array checks the conditions to search on, the second is the actual data you want to update or insert into the new record. So you would still search for a record “Jeff” and “jeff@codebyjeff.com”, and either update its “some_count” to be 12, or create the whole record if not found.</p><p>So there you have it! No more running from the zombies.</p><p>Hope that helped!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*W7CUnE6f0beH_cjF" /></figure><p><em>Originally published at </em><a href="https://oldblog.codebyjeff.com/blog/2016/04/eloquent-create-update-new-the-untold-story"><em>https://oldblog.codebyjeff.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96751ac0e1c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time left strings with Carbon and Laravel string helper]]></title>
            <link>https://medium.com/@codebyjeff/time-left-strings-with-carbon-and-laravel-string-helper-2f6f0594d439?source=rss-a4df2ac24cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f6f0594d439</guid>
            <dc:creator><![CDATA[Jeff Madsen]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 04:15:01 GMT</pubDate>
            <atom:updated>2021-12-20T04:15:01.684Z</atom:updated>
            <content:encoded><![CDATA[<p>Tag: Laravel 5.0+</p><p>This is taken from a post and discussion on <a href="http://codebyjeff.com/newsletter">Laravel Quick Tips</a> that people found to be pretty useful, and so I thought I’d expand on it a little and share.</p><p>I’m sure you’ve all had to do a human-readable “time left” before — for example, an auction countdown where there were “5 hours left!”. Not hard, just messy.</p><p>Unless you’re using Laravel and Carbon. It’s dead easy.</p><p>This can be written in a variety of ways according to your needs. To make it simple to follow along if you want to try it out yourself, I’m just going to use a mutator, but of course the important code can be shifted to a class and made more generic. A downside of doing this in a mutator is that it is tightly coupled to our model and can’t be as easily tested or shared across the application (or reused in other applications without the old “copy/paste” migration technique).</p><p>We’re going to use the example of a product on auction. We need to make a field on our Eloquent model, `expires_at` and — this is important — add it to the $dates array on our model.</p><p>If you aren’t aware, any field added to that array will be cast as a Carbon date. A Carbon date is a class that extends the DateTime object using the <a href="http://carbon.nesbot.com/docs">Carbon Library</a>. This was added to Laravel itself some versions ago, and is used in the Eloquent Model source to cast `created_at` and `updated_at` automatically. You can add any date field of your own and leverage the power of Carbon by simply using:</p><pre>protected $dates = [&#39;expires_at&#39;];</pre><p>Next, I’m adding a function to the model called displayHumanTimeLeft(). I like to think of functions as actions and name them so, so this says exactly what it does. I’ll grab a Carbon instance for right now:</p><pre>public function displayHumanTimeLeft() { $now = Carbon::now(); }</pre><p>Carbon uses `_toString()` to allow you to simply echo your dates, which is why you may not have noticed this before, but it is actually a more complex object.</p><p>From here my version may branch off a bit from what you actually need to display, but I’m just going to show you how to set up “X day(s) left”. We only want to show this if there is at least one day left, otherwise it will drop down to similar code calculating hours, etc.</p><pre>public function displayHumanTimeLeft() { $now = Carbon::now(); if ($now-&gt;diffInDays($this-&gt;expires_at) &gt; 0) { return $now-&gt;diffInDays($this-&gt;expires_at) . str_plural(&#39; day&#39;, $now-&gt;diffInDays($this-&gt;expires_at)). &#39; left&#39;; } }</pre><p>Let’s look at that and see what it’s doing. First, diffInDays() compares two Carbon dates and gives you an integer. So if it is &gt; 0, it will run that code. The second part is why Laravel can be so wonderful at times. We want to use the string “ days left”. But of course, if it is only 1 day, we want the singular.</p><p>If you look in the Illuminate/Support/helpers file, you’ll see that `str_plural()` actually takes a second argument. It defaults to ‘2’, meaning the default will always be the plural form, but if you pass it ‘1’ then the Str::plural will pass it to the ‘Pluralizer’, which will figure out for you if it should pluralize or not.</p><p>So the only thing we have to do is pass to the Carbon::now() our Carbon date we are comparing (`expires_at`), tell it if we want to compare days, hours, etc, and finally feed that to the Laravel helper function. My example is a simpler form — if it is less than a day, it would drop down to find hours instead, then minutes and seconds. You can make the full “4 days, 2 hours, 5 minutes” type string with a little more manipulation.</p><p>That’s it — you’re finished! Have a look at the <a href="http://carbon.nesbot.com/docs/#api-difference">Carbon docs</a> to see the other related functions you may want for finding the difference in other time periods.</p><p>Hope that helps!</p><p><em>Originally published at </em><a href="https://oldblog.codebyjeff.com/blog/2016/04/time-left-strings-with-carbon-and-laravel-string-helper"><em>https://oldblog.codebyjeff.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f6f0594d439" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello, Mr. asdfgh qweefg! Welcome to kgjhjgjh!]]></title>
            <link>https://medium.com/@codebyjeff/hello-mr-asdfgh-qweefg-welcome-to-kgjhjgjh-487afc584deb?source=rss-a4df2ac24cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/487afc584deb</guid>
            <dc:creator><![CDATA[Jeff Madsen]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 04:14:18 GMT</pubDate>
            <atom:updated>2021-12-20T04:14:18.401Z</atom:updated>
            <content:encoded><![CDATA[<p>Tag: Laravel 5.0+, Faker</p><p><strong>Hello, Mr. asdfgh qweefg! Welcome to kgjhjgjh!</strong></p><p>Thank you. Only the name’s not “asdfgh qweefg”.</p><p><strong>Sorry! It’s just easier..</strong></p><p>You’re always showing everyone on <a href="http://codebyjeff.com/newsletter">Laravel Quick Tips</a> these helpful little tricks. Why not show them how to give me a proper name?</p><p><strong>Nice plug! And good idea.</strong></p><pre>//commandline `php artisan make:seeder UserTableSeeder` // UserTableSeeder.php use Illuminate\Database\Seeder; use App\User; class UserTableSeeder extends Seeder { public function run() { User::truncate(); $faker = Faker\Factory::create(); User::create([ &#39;name&#39; =&gt; $faker-&gt;name, &#39;email&#39; =&gt; $faker-&gt;email, &#39;age&#39; =&gt; $faker-&gt;numberBetween(1, 100), &#39;city&#39; =&gt; $faker-&gt;city, ]); } }</pre><p><strong>Hello, Mr. Earnest Wunsch! Welcome to…</strong></p><p>Name’s Davin Tremblay</p><p><strong>But I just made…oh!</strong></p><pre>... $faker-&gt;seed(123); ...</pre><p>Very nice. Except I’m Danish…</p><pre>$faker = Faker\Factory::create(&#39;da_DK&#39;); ...</pre><p><strong>Hans Egholm Erichsen, aged 58, from Ålbæk?</strong></p><p>Well, I’m <em>from</em> Ålbæk, but I live in Spain…</p><pre>$faker = Faker\Factory::create(&#39;da_DK&#39;); $faker-&gt;seed(123); $faker_sp = Faker\Factory::create(&#39;es_ES&#39;); $faker_sp-&gt;seed(123); User::create([ &#39;name&#39; =&gt; $faker-&gt;name, &#39;email&#39; =&gt; $faker-&gt;email, &#39;age&#39; =&gt; $faker-&gt;numberBetween(1, 100), &#39;city&#39; =&gt; $faker_sp-&gt;city, ]);</pre><p>Lovely! Now…if I just had a few friends…</p><pre>for ($i = 0; $i &lt; 500; $i++) { User::create([ &#39;name&#39; =&gt; $faker-&gt;name, &#39;email&#39; =&gt; $faker-&gt;email, &#39;age&#39; =&gt; $faker-&gt;numberBetween(1, 100), &#39;city&#39; =&gt; $faker_sp-&gt;city, ]); }</pre><p>Not sure I need <em>that</em> many friends. But more important, why so many babies and Old Farts? Can’t you get more of them closer to my age?</p><pre>... &#39;age&#39; =&gt; $faker-&gt;optional($weight = 0.4, $default = 58)-&gt;numberBetween(1, 100),</pre><p>40% of us are 58 years old? You might have tried a standard deviation.</p><p><strong>I have to leave something for the readers or they’ll feel spoon fed. Why are you using “Gunnar.Stokholm@hotmail.com” for an email?</strong></p><p>Because you left that for the readers…?</p><pre>for ($i = 0; $i &lt; 500; $i++) { $name = $faker-&gt;name; // add a random number when using so many values, to ensure random emails $email = str_replace(&#39; &#39;, &#39;.&#39;, (strtolower($name))) . $faker-&gt;numberBetween(1, 100) . &#39;.mail.dk&#39;; User::create([ &#39;name&#39; =&gt; $name, &#39;email&#39; =&gt; $email, &#39;age&#39; =&gt; $faker-&gt;optional($weight = 0.4, $default = 58)-&gt;numberBetween(1, 100), &#39;city&#39; =&gt; $faker_sp-&gt;city, ]); }</pre><p>That’s pretty good! You want my driver’s license, as well? 25AW-657-QAZ</p><pre>... &#39;license&#39; =&gt; strtoupper($faker-&gt;bothify(&#39;##??-###-???&#39;)),</pre><p>Great! Now if you just add our dogs, we’ll be all set.</p><p><strong>Dogs? What kind of dogs?</strong></p><p>Poodles, collies and Dobermans. We don’t all have them, but no one has more than three.</p><pre>// factories/ModelFactory.php ... $factory-&gt;define(App\Dogs::class, function (Faker\Generator $faker) { return [ &#39;name&#39; =&gt; $faker-&gt;firstName, &#39;age&#39; =&gt; $faker-&gt;randomDigit, &#39;breed&#39; =&gt; $faker-&gt;randomElement([&#39;Boxer&#39;, &#39;Border Collie&#39;, &#39;Doberman Pinscher&#39;]), ]; }); // UserTableSeeder.php use App\User; use App\Dogs; ... User::truncate(); Dogs::truncate(); ... $user = User::create([ &#39;name&#39; =&gt; $name, &#39;email&#39; =&gt; $email, &#39;age&#39; =&gt; $faker-&gt;optional($weight = 0.4, $default = 58)-&gt;numberBetween(1, 100), &#39;city&#39; =&gt; $faker_sp-&gt;city, &#39;license&#39; =&gt; strtoupper($faker-&gt;bothify(&#39;##??-###-???&#39;)), ]); foreach (range(0, rand(0, 3)) as $value) { $user-&gt;dogs()-&gt;save(factory(App\Dogs::class)-&gt;make()); }</pre><p>That’s nifty. The `dogs` table has a user_id field and relationships, so it gets automatically populated this way? Why didn’t you use the default User factory model?</p><p><strong>I wanted to show the simpler way first. It would be better to use the factory so we could recreate them for all our tests without duplicating code.</strong></p><p>What if I wanted all our dogs’ names to be Klingon?</p><p><strong>Make your own Provider for Klingon language like this: </strong><a href="https://github.com/fzaninotto/Faker#faker-internals-understanding-providers"><strong>Faker Internals: Understanding Providers</strong></a><strong>. Be sure to submit it as a PR afterwards, to build up the data library.</strong></p><p>Great! So…why were you calling me “Mr. asdfgh qweefg” at the beginning of this?</p><p><strong>It was…easier…</strong></p><p>Mmmmm. How are your tests?</p><p><strong>Author’s Note:</strong> I used Laravel’s Seeding &amp; Factory Model code, but if you are using something else to build your app, <a href="http://docs.phinx.org/">Phinx</a> is wonderful and has Seeders, and of course <a href="https://factory-muffin.thephpleague.com/">Factory Muffin</a> will do your Factory Model work for you.</p><p>Please let me know if any of the code was confusing because of the style I chose to write this in.</p><p>Hope that helps!</p><p><em>Originally published at </em><a href="https://oldblog.codebyjeff.com/blog/2016/04/hello-mr-asdfgh-qweefg-welcome-to-kgjhjgjh"><em>https://oldblog.codebyjeff.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=487afc584deb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[codebyjeff — Getting into an Eloquent State of Mind]]></title>
            <link>https://medium.com/@codebyjeff/codebyjeff-getting-into-an-eloquent-state-of-mind-f9f93bf29d59?source=rss-a4df2ac24cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9f93bf29d59</guid>
            <dc:creator><![CDATA[Jeff Madsen]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 04:13:34 GMT</pubDate>
            <atom:updated>2021-12-20T04:13:34.944Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting into an Eloquent State of Mind</h3><p>Tag: Laravel v5.0+</p><p>I’m a bit of a bouldering fanatic these days. When I first started about a year ago, I was a typical clumsy beginner; butt hanging out, feet scrambling noisily against the wall, searching blindly for toeholds, grasping and gasping for that handhold just out of reach.</p><p>Lately I’ve noticed a change. Where I used to stretch as far as I could for a handle, I now shift my body and grab it easily. Where I used to see a jug impossibly out of reach, I now reach up with a leg and make a heel hook. Routes that initially took me weeks to conquer I glide up effortlessly as a warm up. I didn’t just get stronger; I changed.</p><p>What changed? I understand my body differently. Handles can be grasped in different ways. Legs aren’t only for climbing straight up the wall like a ladder.</p><p>I look at the way I learned (am learning) Eloquent the same way. Being an Active Record pattern, it is easy to look at it as just a way to help write your sql statements. That is like the beginner climber who sees the handles on the wall as just a fancy ladder. It <em>is</em>, in a way, but clearly you’ll never get good at it thinking that way.</p><p>Over at my <a href="http://codebyjeff.com/newsletter">Quick Tips</a> newsletter I’ve been showing a few functions and uses of the Eloquent Model class that I think are both under-utilized and important for refactoring into cleaner code. Being a short weekly email, though, I don’t really get to delve deeper than “here’s a better way”.</p><p>Many developers mix Eloquent and the underlying QueryBuilder and never think of the difference between the two. They want to produce sql statements, and use these classes to substitute writing them long-hand or to allow them to make reusable parts. Just like the “fancy ladder” at the climbing gym, however, there’s a different way of looking at Eloquent</p><p>The ORM isn’t just grabbing datarows; it is creating Model instances and populating them. Those are two very different ideas. Look at this, for example:</p><pre>$user = User::find(1); dump($user-&gt;id);</pre><p>If there is no matching row in the table, this will throw an error. We want to take the id from row number 1, but there is no row number 1, so how can we get its id? It blows up on us. Compare to this:</p><pre>$user = User::findOrNew(1); dump($user-&gt;id);</pre><p>This works fine; $user-&gt;id is null.</p><p>In the second case, we are saying, “Go get me a Model instance. See if you can populate it with a certain row from the db, but even if you can’t, I want the model.” I’m not thinking about the database, I’m thinking about my classes. I can clean up my code because I can safely and consistently pass the result into some function or class that is expecting an Eloquent\Model instance and let it deal with the id being populated or not, in the same way I would inject any of my other classes. I’m thinking in objects now.</p><pre>// thinking about databases $post = Post::create([&#39;title&#39; =&gt; &#39;The title&#39;, &#39;user_id&#39; =&gt; 1]); // thinking about objects $post = Post::create([&#39;title&#39; =&gt; &#39;The title&#39;]); User::find(1)-&gt;posts()-&gt;save($post);</pre><p>In the second case, I am thinking, “I have a User class instance. It has a Collection of zero-to-many Post instances, to which I want to add this new Post instance”.</p><p>Admittedly, all of this seems very much like we are over-thinking everything. Most simple examples do. When we start building up more complex code and classes is where we see the benefit; when we are deep inside some class function we have injected a User instance into and we realize we have a collection of posts we can manipulate, we will start to feel like we are “gliding up the wall” in Eloquent.</p><p>Hope that helps!</p><p><em>Originally published at </em><a href="https://oldblog.codebyjeff.com/blog/2016/05/getting-into-an-eloquent-state-of-mind"><em>https://oldblog.codebyjeff.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9f93bf29d59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[codebyjeff — The Mahana Bitfield Library for Settings Sanity]]></title>
            <link>https://medium.com/@codebyjeff/codebyjeff-the-mahana-bitfield-library-for-settings-sanity-8b25ff5da59b?source=rss-a4df2ac24cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b25ff5da59b</guid>
            <dc:creator><![CDATA[Jeff Madsen]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 04:12:46 GMT</pubDate>
            <atom:updated>2021-12-20T04:12:46.095Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Mahana Bitfield Library for Settings Sanity</h3><p>Tag: PHP v5.0+</p><p>Driven crazy with all the flags being constantly added to your tables? Migrations files stacked higher than the *other* Jeff Madsen’s poker chips at a championship game? Have no fear!</p><p><a href="https://github.com/jrmadsen67/mahana-bitmask">The Mahana Bitfield Library</a> is a simple and useful library. Using <a href="https://en.wikipedia.org/wiki/Mask_%28computing%29">Bitfield Masking</a> we can condense up to 31 separate flags to a single integer setting in much the same way that Unix permission are used.</p><p>The READ.ME explains the setup, but in short, you 1) created a new class that inherits from MahanaBitfield abstract class, 2) set up the flags you want in your new class, 3) there is no three — you just use it now.</p><p>So given a set of flags such as:</p><pre>public $flags = [ &#39;flag1&#39; =&gt; 0, &#39;flag2&#39; =&gt; 1, &#39;flag3&#39; =&gt; 2, ];</pre><p>You can set each one to true or false. The bitmasking calculates a unique value for that particular arrangement. Each flag’s `value` is double the preceding one, and all the “true” settings are added up.</p><pre>$settings = [ &#39;flag1&#39; =&gt; true, &#39;flag2&#39; =&gt; false, &#39;flag3&#39; =&gt; true, ]; // 1 + 0 + 4 = 5 $settings = [ &#39;flag1&#39; =&gt; false, &#39;flag2&#39; =&gt; true, &#39;flag3&#39; =&gt; true, ]; // 0 + 2 + 4 = 6</pre><p>Those values are not anything you even have to worry about — it is all calculated internally. If you need to get or set a particular flag, use:</p><pre>$user_settings-&gt;flag1 = true; // or $flag1 = $user_settings-&gt;flag1</pre><p>The array methods `getFlags` and `setFlags` were made to allow you to easily pass values back and forth from your forms.</p><p>Special thanks to <a href="https://twitter.com/dfcowell">Dan Cowell</a> whose suggestions greatly improved the usability.</p><p>Hope that helps!</p><p><em>Originally published at </em><a href="https://oldblog.codebyjeff.com/blog/2016/05/the-mahana-bitfield-library-for-settings-sanity"><em>https://oldblog.codebyjeff.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b25ff5da59b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>