<?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 Spotwilliams on Medium]]></title>
        <description><![CDATA[Stories by Spotwilliams on Medium]]></description>
        <link>https://medium.com/@ricardovergarawork?source=rss-c14896ebfe6a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Kwr_nGQV7ymEpc3CPi5tUg.jpeg</url>
            <title>Stories by Spotwilliams on Medium</title>
            <link>https://medium.com/@ricardovergarawork?source=rss-c14896ebfe6a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 20:33:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ricardovergarawork/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[Using models and migrations exclusively for testing support in Laravel]]></title>
            <link>https://medium.com/@ricardovergarawork/using-models-and-migrations-exclusively-for-testing-support-in-laravel-aa797dec4fde?source=rss-c14896ebfe6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa797dec4fde</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Spotwilliams]]></dc:creator>
            <pubDate>Thu, 09 May 2024 08:55:17 GMT</pubDate>
            <atom:updated>2024-05-09T08:55:17.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qFYiBfIkPbmHTYLaiCrYKQ.jpeg" /></figure><h4>Introduction</h4><p>As developers, we’re constantly striving for robust code, which naturally leads us into the realm of rigorous testing. However, within the intricate maze of long-standing projects, we frequently encounter challenges that extend far beyond our immediate objectives. Consider the journey of Eloquent models: what begins as a modest abstraction can easily become a very wide and heavily-loaded class, with numerous responsibilities, non-nullable columns, and dependencies.</p><p>Let’s envision a scenario involving a “Data Importer” module. Here, the objective is clear: to ingest data from diverse sources, apply transformations, validations, orchestrations, and finally, persist the refined data.</p><p>In this scenario, and for the sake of this post, let’s focus on the critical aspect of testing: the ability to read from different sources and prepare the data for storage. While persistence might seem trivial in comparison, testing should ideally revolve around the core process, rather than wrestling with the complexities of sprawling models.</p><p>However, in our profession, we often find ourselves spending considerable time preparing or modifying tests merely to accommodate the storage of data using these models. This is typically due to the presence of bloated models with excessive columns or overly complex responsibilities, turning the testing journey into an uphill battle.</p><p>In this post, I’ll demonstrate how to create models and their migrations solely for use in tests, without integrating them into the main codebase, yet accessible from the test cases.</p><h4>Let’s write code</h4><p>Let’s dive into writing some code. The first step is to craft a straightforward Eloquent model intended solely for our testing purposes. While there’s nothing particularly groundbreaking about this process, it’s crucial to pay attention to the namespace. Unlike typical Eloquent models residing in the app/Models folder, this one will be located under tests/Support/Models.</p><pre>&lt;?php<br><br>declare(strict_types=1);<br><br>namespace Tests\Support\Models;<br><br>use Carbon\Carbon;<br>use Illuminate\Database\Eloquent\Model;<br><br>/**<br> * @property string name<br> * @property integer value<br> * @property boolean valid<br> * @property Carbon date<br> * @property string|null detail<br> */<br>class TestModel extends Model<br>{<br>    public $fillable = [<br>        &#39;name&#39;,<br>        &#39;value&#39;,<br>        &#39;valid&#39;,<br>        &#39;date&#39;,<br>        &#39;detail&#39;,<br>    ];<br><br>    protected $casts = [<br>        &#39;value&#39; =&gt; &#39;integer&#39;,<br>        &#39;valid&#39; =&gt; &#39;boolean&#39;,<br>        &#39;date&#39; =&gt; &#39;date&#39;,<br>    ];<br>}</pre><p>Now, let’s proceed by creating a migration that outlines the model from a database perspective. To ensure separation from the actual migrations, we’ll place this migration under tests/Support/database/migrations/create_test_models_table.php.</p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    public function up()<br>    {<br>        Schema::create(&#39;test_models&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;integer(&#39;value&#39;);<br>            $table-&gt;boolean(&#39;valid&#39;);<br>            $table-&gt;date(&#39;date&#39;);<br>            $table-&gt;string(&#39;detail&#39;)-&gt;nullable();<br>            $table-&gt;timestamps();<br>        });<br>    }<br>};</pre><p>Now, let’s put our setup to the test. We’ll create a test class to ensure that we can effectively utilize the new class, and more importantly, verify our ability to populate the database using this dummy model. <br>Please, pay special attention to the setUp method; this is where we specify that certain migrations must be executed to enable the use of our new dummy model.</p><pre>&lt;?php<br><br>declare(strict_types=1);<br><br>namespace Tests;<br><br>use Carbon\Carbon;<br>use Illuminate\Foundation\Testing\RefreshDatabase;<br>use Illuminate\Support\Facades\Artisan;<br>use Tests\Support\Models\TestModel;<br><br>class TestCanUseModelsOnlyForTestingSupport extends TestCase<br>{<br>    use RefreshDatabase;<br><br>    protected function setUp(): void<br>    {<br>        parent::setUp();<br>        Artisan::call(&#39;migrate&#39;, [&#39;--path&#39; =&gt; __DIR__ . &#39;/Support/database/migrations/create_test_models_table.php&#39;, &#39;--realpath&#39; =&gt; true]);<br><br>    }<br><br>    public function test_model_test_can_be_used()<br>    {<br>        $model = new TestModel();<br><br>        $model-&gt;name = &#39;Test model&#39;;<br>        $model-&gt;value = 1500;<br>        $model-&gt;valid = true;<br>        $model-&gt;date = Carbon::today();<br>        $model-&gt;detail = null;<br><br>        $model-&gt;save();<br><br>        $this-&gt;assertNotNull(TestModel::first());<br>    }<br>}</pre><p>Ensure that this autoload configuration is present in your composer.json file. This tells Composer to autoload any classes under the Tests namespace from the tests folder.</p><p>Make sure to run composer dump-autoload after making changes to the composer.json file to regenerate the Composer autoloader.</p><pre>{<br>  ...<br><br>    &quot;autoload-dev&quot;: {<br>        &quot;psr-4&quot;: {<br>            &quot;Tests\\&quot;: &quot;tests/&quot;<br>        }<br>    },<br>}</pre><p>In conclusion, adopting dedicated models and migrations for testing in Laravel can greatly streamline our testing process. By ensuring Composer recognizes the tests folder for namespace generation, we can efficiently conduct targeted tests without the complexities of production code. I hope you find these tips helpful for improving your testing workflow in Laravel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa797dec4fde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[PHP] Writing my own input validator just for fun]]></title>
            <link>https://medium.com/@ricardovergarawork/php-writing-my-own-input-validator-just-for-fun-39ffbea1a342?source=rss-c14896ebfe6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/39ffbea1a342</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[composer]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Spotwilliams]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 20:25:22 GMT</pubDate>
            <atom:updated>2023-09-11T20:25:22.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDQ6NwvpKqeHrzcXLrVxlw.jpeg" /><figcaption>Loving php since…</figcaption></figure><p>Some time ago, someone requested that I create a validation feature without relying on any framework or package. I won’t delve into the reasons behind this request, but after completing the task, I believe it could be valuable to share our experience.</p><p>One of the reasons for sharing this (aside from the fact that we had some fun building and sharing it) is that you might encounter situations where you initially think a problem can be easily solved by adding a package or using a framework. However, as time goes by, it often becomes clear that the feature requires customization and simplicity. Perhaps, after trying out the package, you realize that it could have been easier if you had taken the time to do it yourself. I want to clarify that I’m not opposed to using pre-built solutions, but sometimes, doing it ourselves is the best approach.</p><p>With that introduction, let’s now shift our focus to the code, shall we?</p><h3><strong>The problem</strong></h3><p>We need to find a method for validating input data, taking into account that certain inputs may need to meet various conditions. For instance, consider an “age” field that not only needs to adhere to a specific format but also be located within a certain range.</p><h3>The Approach</h3><p>As I mentioned earlier, I opted not to rely on any pre-existing solutions. However, there’s no prohibition against drawing inspiration from them. Being a PHP developer with a solid background in Laravel, I chose to take inspiration from the concept of validation using a list of rules to apply to the data.</p><p>So, following Laravel’s style, the fundamental idea should guide us to create a class that can be utilized in the following manner:</p><pre><br>$validator = new Validator();<br><br>// The validator should allow receiving a list of values and <br>// a list of rules to apply, returning true if validation<br>// succeeds and throwing a validation exception if a rule fails.<br>$validator-&gt;validate(values: [], rules: []);<br><br>// A clearer example of formats would be:<br>$result = $validator-&gt;validate(values: [&#39;field_1&#39; =&gt; &#39;value&#39;], rules: [&#39;field_1&#39; =&gt; [&#39;required&#39;]]);</pre><p>So, one significant difference from Laravel is that in our case, we will provide an array of rules instead of a long string separated by the `|` character. Following the array style makes it easier for us to pass values by reference, as demonstrated below:</p><pre>$result = $validator-&gt;validate(<br>    values: [&#39;field_1&#39; =&gt; &#39;value&#39;],<br>    rules: [&#39;field_1&#39; =&gt; [&#39;required&#39;, &#39;gt&#39; =&gt; 300,]<br>]);</pre><p>Once we have defined how to use the validator, we need to write the validate method. The general approach is to iterate through the list of provided rules. This involves a double iteration: the first loop gives us access to the field name, and the second loop iterates over the rules for that field. Once we have the field name, the rule name, and the potential constraints of the rule, we attempt to find the code that handles the validation based on the rule name.</p><p>I won’t include the code that implements what I’ve explained here, but you can find it at the end of this article in the repository, where you’ll be able to see the loops and specific details.</p><h3>The Fun Part</h3><p>What makes this truly enjoyable is implementing various rules and providing the opportunity to extend the list of existing rules (or even overwrite existing ones) without the need to modify existing code.</p><p>To achieve this while adhering to the valuable SOLID principles, let’s imagine that we have an array where each key represents the name of a rule and the corresponding value contains the code that handles it:</p><pre>[<br>  &#39;required&#39; =&gt; SomeClass::class,<br>  &#39;max&#39; =&gt; SomeSecondClass::class,<br>]</pre><p>Now, to implement this concept, we could create a contract like this:</p><pre>interface ValidationRule<br>{<br>    /**<br>     * Applies the validation rule to a field&#39;s value.<br>     *<br>     * @param string $ruleName The name of the rule being applied.<br>     * @param string $field The name of the field being validated.<br>     * @param mixed|null $value The value of the field being validated.<br>     * @param mixed|null $constraint Any additional constraint required for the validation rule.<br>     * @return bool Whether the validation rule succeeded.<br>     * @throws ValidationFailed If the validation rule fails.<br>     */<br>    public function apply(string $ruleName, string $field, mixed $value = null, $constraint = null): bool;<br>}</pre><p>Once we have a contract, all rules should implement this interface. For example:</p><pre>use ValidationFailed;<br>use ValidationRule;<br><br>class Required implements ValidationRule<br>{<br>    /** @inheritDoc */<br>    public function apply(string $ruleName, string $field, mixed $value = null, $constraint = null): bool<br>    {<br>        if ($value !== null) {<br>            return true;<br>        }<br>        throw new ValidationFailed(&quot;The field `{$field}` is required.&quot;);<br>    }<br>}</pre><p>A good approach is to store the array containing the list of available validation rules outside of the `Validator` class. This way, every time we want to create a new rule, we won’t need to modify the class itself. To achieve this, we can utilize a configuration file, such as:</p><pre>use Rules;<br><br>return [<br>    &#39;rules&#39; =&gt; [<br>        &#39;required&#39; =&gt; Rules\Required::class,<br>        // ...<br>    ]<br>];</pre><p>And that’s it!</p><h3>Saying good bye</h3><p>For those interested in exploring this validation concept further and examining the actual code implementation, I’ve made the full repository available on GitHub, including tests! You can access it by visiting the following link <a href="https://github.com/spotwilliams/validator">Validator Repository</a>. Feel free to explore, experiment, and why not contribute.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39ffbea1a342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Laravel Command to refresh a group of migrations]]></title>
            <link>https://medium.com/@ricardovergarawork/simple-laravel-command-to-refresh-a-group-of-migrations-d0c08c30f6e2?source=rss-c14896ebfe6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0c08c30f6e2</guid>
            <category><![CDATA[developer-stories]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[laravel-migrations]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Spotwilliams]]></dc:creator>
            <pubDate>Wed, 02 Aug 2023 09:20:19 GMT</pubDate>
            <atom:updated>2023-08-08T13:17:13.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7PLc-qOvWDhurM7-ttmLw.jpeg" /></figure><p>Like every Laravel developer, I rely on migrations to perform changes on the database. For those who are not familiar, here’s what Laravel’s documentation tells us about migrations:</p><blockquote>Migrations are like version control for your database, allowing your team to define and share the application’s database schema definition.</blockquote><p>So, basically, migrations are anonymous classes stored under the /database/migrations folder, and they are accessed and executed once when we use the command php artisan migrate. After a migration is executed, Laravel stores the name of the file where the class exists in a database table (migrations table). As a result, the next time the command is executed, Laravel will skip the execution of those migrations that are already listed in the migrations table.</p><p>The framework also provides a way to rollback the changes that a migration performs on the database. You can execute the php artisan migrate:rollback command, and Laravel will iterate from the latest to the first migration and execute the rollback code related to each migration. If you&#39;re not familiar with these terms, please refer to <a href="https://laravel.com/docs/10.x/migrations#introduction">Laravel Migration&#39;s</a> documentation for more details.</p><p>Something very useful with the rollback command is that you can specify how many migrations can be rolled back by adding --step=&lt;number&gt;. This way, Laravel will only rollback the specified number of migrations instead of going through all of them.</p><p>Laravel also provides some very helpful commands called migrate:fresh and migrate:refresh.</p><ul><li>migrate:fresh drops the entire database schema and then executes all migrations from the beginning.</li><li>migrate:refresh first rolls back all migrations and then executes all of them again. These commands can be handy in certain scenarios when you need to reset the database to a clean state.</li></ul><p>This is very handy when you need to “reset” your database, but what about when you want to “refresh” only certain migrations instead of all of them? In my case, when I’m frequently working with changes on the database, I find myself repeatedly testing migrations, making updates, rolling back, and then migrating again. This process involves executing two separate commands after modifying a migration (using rollback with the --step parameter and then migrate).</p><p>Considering the repetitive nature of this task, it would be helpful if Laravel had a command to refresh a specific group of migrations, rather than refreshing all of them. While it may seem trivial, facing the same situation multiple times in a short period can become frustrating. Therefore, I decided to invest some of my time to create a custom command that handles this for me. It’s not procrastination; rather, it’s an investment in my peace of mind and productivity.</p><p>So, long short story, here’s the command:</p><pre>&lt;?php<br><br>namespace App\Console\Commands;<br><br>use Illuminate\Console\Command;<br>use Illuminate\Support\Facades\DB;<br>use Illuminate\Support\Facades\Validator;<br><br>class DatabaseRefreshWithStep extends Command<br>{<br>    protected $signature = &#39;migrate:refresh:step <br>        {steps? : Indicates the number of steps to rollback, if non provided will see the list of migrations that were executed on DB} <br>        {--seed : Indicates if the seed task should be re-run}<br>    &#39;;<br><br>    protected $description = &#39;Performs rollback and re-run migration as much steps as indicate in the param&#39;;<br><br>    public function handle()<br>    {<br>        $steps = $this-&gt;argument(&#39;steps&#39;);<br><br>        if ($steps === null) {<br>            $this-&gt;renderMigrationsTable();<br>            $steps = $this-&gt;ask(&#39;Please, indicate the number of steps that want to reset&#39;);<br><br>        }<br><br>        $validator = Validator::make(data: [&#39;steps&#39; =&gt; $steps], rules: [&#39;steps&#39; =&gt; &#39;required|integer&#39;]);<br><br>        if ($validator-&gt;fails()) {<br>            $this-&gt;error(&#39;Argument `steps` is required and must be integer&#39;);<br>            return Command::FAILURE;<br>        }<br><br>        $this-&gt;call(&#39;migrate:rollback&#39;, [&#39;--step&#39; =&gt; $steps]);<br><br>        $this-&gt;call(&#39;migrate&#39;, $this-&gt;option(&#39;seed&#39;) ? [&#39;--seed&#39; =&gt; true] : []);<br><br>        return Command::SUCCESS;<br>    }<br><br>    private function renderMigrationsTable(): void<br>    {<br>        $migrations = DB::table(&#39;migrations&#39;)-&gt;get();<br>        $rows = $migrations-&gt;mapWithKeys(fn($std, $key) =&gt; [$key =&gt; [&#39;step&#39; =&gt; ($migrations-&gt;count() - $key), &#39;migration&#39; =&gt; $std-&gt;migration]]);<br><br>        $this-&gt;table(headers: [&#39;Step&#39;, &#39;Migrations&#39;,], rows: $rows);<br>    }<br>}</pre><p>Very brief explanation of what this class does (I asked to ChatGPT to write this but wasn&#39;t very helpful, so here are my fingers typing):</p><p>You can execute php artisan migrate:refresh:step &lt;number&gt;, and it will automatically perform a rollback and then re-migrate the exact number of steps indicated by &lt;number&gt;. If &lt;number&gt; is not provided, the command will display a list of already executed migrations and prompt you to enter the desired number of steps (with validations to accept only integer values).</p><p>Additionally, you have the option to append -seed to the command to execute seeders after the migration.</p><p>If you find this command helpful, you can consider integrating it into your Laravel project. As for tweaks or improvements, it would depend on your specific needs and use cases. Some potential enhancements could include error handling, interactive prompts for other options, or additional features to make the migration process even smoother. Feel free to customize it based on your requirements!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0c08c30f6e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplified EAV Laravel implementation]]></title>
            <link>https://medium.com/@ricardovergarawork/simplified-eav-laravel-implementation-7a54e9f89240?source=rss-c14896ebfe6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a54e9f89240</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[eav]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Spotwilliams]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 06:08:25 GMT</pubDate>
            <atom:updated>2023-09-06T14:10:00.372Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simplified EAV Laravel implementation [Updated]</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqHxMouuYemwD480Wi5ppg.jpeg" /></figure><p>Another day at work, another call with our client requesting changes to the data structure for storing additional information or improving data storage efficiency. It feels like being trapped in a never-ending cycle of updating the database to properly represent the client’s data.</p><blockquote>Have you ever had a dream, Neo, that you were so sure was real? What if you were unable to wake from that dream? How would you know the difference between the dream world and the real world? — Morpheus</blockquote><p>Have you ever felt that you’re in a dream, and every day is the same as before? In software development, it happens a lot, particularly in projects where clients or businesses continually request updates to the data structure, requiring our constant efforts to ensure accuracy.</p><p>There is a pattern that can assist us in minimizing the need for frequent database alterations. It proves especially valuable in projects that aim to share a codebase among multiple clients or in customizable platforms like Magento, where data representation must accommodate the unique requirements of each client. This pattern is called Entity-Attribute-Value (EAV), which essentially enables the storage of both data and structure together as rows in the database.</p><p>In this post, I will introduce a simplified version of the EAV pattern that eliminates the need for a separate Entity model. Instead, we can leverage the specific model itself, which simplifies our code. This approach streamlines the implementation process and enables us to directly interact with the relevant models, resulting in reduced complexity and enhanced code readability.</p><p>For example, let’s consider a model called Person (keeping in line with the Laravel context). Initially, we might envision a straightforward list of attributes for this model, such as full name, age, birthdate, and money in the pocket. The conventional approach would resemble the following code snippet:</p><pre>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Model;<br><br>class Person extends Model<br>{<br>  protected $table = &quot;people&quot;;<br><br>  protected $fillable = [<br>        &#39;full_name&#39;,<br>        &#39;birthdate&#39;,<br>        &#39;age&#39;,<br>        &#39;savings&#39;,<br>    ];<br>}</pre><p>To transform this into a simplified EAV model, we need to introduce two additional models and modify the Person model accordingly. We should remove the attributes from the $fillable array in the Person model. The first new model will represent the list of attributes associated with the Person model, while the second model will hold the values associated with a particular person and attribute.</p><pre><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br><br>class CustomAttribute extends Model<br>{<br>    use HasFactory;<br><br>    protected $fillable = [<br>        &#39;label&#39;,<br>        &#39;name&#39;,<br>        &#39;type&#39;,<br>        &#39;column_name&#39;,<br>    ];<br>}</pre><p>The provided code snippet offers a concise portrayal of an attribute. Two crucial components are emphasized: the `name` and the `column_name`. The name represents the attribute’s identifier and is employed to retrieve data from the database when querying information for a single Person or multiple Persons. In contrast, the `column_name` specifies the specific column in the values table that stores the data corresponding to the attribute.</p><p>Next, create the Value model class:</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\BelongsTo;<br><br>class Value extends Model<br>{<br>    use HasFactory;<br><br>    protected $fillable = [<br>        &#39;money_value&#39;,<br>        &#39;string_value&#39;,<br>        &#39;bool_value&#39;,<br>        &#39;integer_value&#39;,<br>        &#39;date_value&#39;,<br>        &#39;timestamp_value&#39;,<br>        &#39;time_value&#39;,<br><br>        &#39;column_name&#39;,<br>        &#39;custom_attribute_id&#39;,<br>    ];<br><br>    public function person(): BelongsTo<br>    {<br>        return $this-&gt;belongsTo(Person::class);<br>    }<br><br>    public function customAttribute(): BelongsTo<br>    {<br>        return $this-&gt;belongsTo(CustomAttribute::class);<br>    }<br>}</pre><p>The Value class is responsible for storing the actual data and provides a means to specify the corresponding column being utilized. In this implementation, the `column_name` attribute is present both in the Value model and the CustomAttribute model. This redundancy is intentional and serves to simplify the code. Frequently, there is a need to examine the Value class independently, without requiring any join or association with the CustomAttribute class.</p><p>Once we have the model structure defined, let’s proceed with populating the data. Here’s an example of how to register a CustomAttribute:</p><pre>// DatabaseSeeder.php<br><br>$person = Person::create();<br><br>$attribute = CustomAttribute::create([<br>    &#39;name&#39; =&gt; &#39;full_name&#39;,<br>    &#39;label&#39; =&gt; &#39;Full name&#39;,<br>    &#39;type&#39; =&gt; &#39;string&#39;,<br>    &#39;column_name&#39; =&gt; &#39;string_value&#39;,<br>]);<br><br>$value = Value::create([<br>    &#39;column_name&#39; =&gt; $attribute-&gt;column_name,<br>    $attribute-&gt;column_name =&gt; &#39;Jhon Doe&#39;,<br>    &#39;custom_attribute_id&#39; =&gt; $attribute-&gt;id,<br>]);<br><br>$person-&gt;values()-&gt;saveMany([$value]);</pre><p>The code snippet provided above serves as a simplified and manual example of how to utilize the current data structure.</p><p>Now, let’s proceed to build a straightforward endpoint that allows us to retrieve the list of persons in the system along with their attributes. In this scenario, envision an SPA (Single Page Application) with a separate team of frontend developers. As the backend developer responsible for the data retrieval, your task is to return the data in a suitable format that the frontend can readily utilize without requiring any additional transformations. Something like this:</p><pre>[<br>  {<br>    &quot;id&quot; : &quot;1&quot;,<br>    &quot;full_name&quot;: &quot;Jhon Doe&quot;,<br>    &quot;age&quot;: 35,<br>    &quot;savings&quot;: 10000.5,<br>  },<br>  ...<br>]</pre><p>There are several ways to prepare the data in the required format. The most obvious approach is to leverage the framework and utilize collection mapping methods to structure the data accordingly. However, what if we could retrieve the data from the database already formatted? So, we would like to execute a query and have a result like this:</p><figure><img alt="database result" src="https://cdn-images-1.medium.com/max/1024/1*xnk0clYPo0B9B7eAxF_kHA.png" /></figure><p>So, an excellent approach is to configure the model itself to retrieve the data in the desired structure. To accomplish this, let’s create a scope method:</p><pre>class Person extends Model {<br>    //...<br><br>    public function scopeWithCustomAttributes(Builder $query): void<br>    {<br>        /** @var Collection&lt;CustomAttribute&gt; $attributes */<br>        $attributes = CustomAttribute::all();<br><br>        $selects = [];<br>        // Build the select list: the header of the query result will have<br>        // the list of fields (ids) and the values will be located at the same level.<br>        // as result we will have in one row all the values of the person.<br>        foreach ($attributes as $attribute) {<br>            // Select the value for the associate field and the current record (current record in the context of the query)<br>            $selects[] = &quot;(SELECT {$attribute-&gt;column_name} FROM values where custom_attribute_id = {$attribute-&gt;id} and values.person_id = people.id) as {$attribute-&gt;name}&quot;;<br>        }<br><br>        $selects = implode(&#39;,&#39;, $selects);<br><br>        $query-&gt;selectRaw(&quot;{$selects}&quot;);<br>    }<br>}</pre><p>The goal of the scopeWithCustomAttributes scope is to modify the query to retrieve the data with each attribute&#39;s value located in the same row, resulting in a more structured and convenient result set. It achieves this by constructing subqueries for each custom attribute, selecting the corresponding value from the values table based on the custom_attribute_id and person_id associations. The constructed SQL query would look similar to this:</p><pre>SELECT<br>    (SELECT column_name_1 FROM values WHERE custom_attribute_id = 1 AND values.person_id = people.id) as attribute_name_1,<br>    (SELECT column_name_2 FROM values WHERE custom_attribute_id = 2 AND values.person_id = people.id) as attribute_name_2,<br>    ...<br>FROM<br>    people</pre><p>In this query, column_name_1, column_name_2, and so on represent the column names storing the attribute values, while attribute_name_1, attribute_name_2, and so on correspond to the attribute names. The query retrieves the values from the values table based on the custom attribute and person associations, and the result set organizes the attribute values in the same row for each person. A final version of the same query would look like this:</p><pre>select (SELECT string_value FROM values where custom_attribute_id = 1 and values.person_id = people.id)  as full_name,<br>       (SELECT date_value FROM values where custom_attribute_id = 2 and values.person_id = people.id)    as birthdate,<br>       (SELECT integer_value FROM values where custom_attribute_id = 3 and values.person_id = people.id) as age,<br>       (SELECT money_value FROM values where custom_attribute_id = 4 and values.person_id = people.id)   as savings<br>from people</pre><p>Now, you can directly utilize the defined scope and retrieve the data in the desired format. By applying the `scopeWithCustomAttributes` scope to your query, the data will be fetched with each attribute’s value conveniently located in the same row. This allows for straightforward access to the data without requiring additional transformations or formatting steps.</p><pre>Route::get(&#39;/people&#39;, function () {<br>    return response()<br>        -&gt;json(<br>            \App\Models\Person::query()<br>                -&gt;withCustomAttributes()<br>                -&gt;paginate(10)<br>                -&gt;withQueryString()<br>        );<br>});</pre><p>In this post, we explored the concept of Entity-Attribute-Value (EAV) pattern and its implementation in Laravel. The EAV pattern is beneficial in scenarios where there is a need for dynamic and customizable data structures. We discussed how to create models such as CustomAttribute, Value, and Person to represent attributes, attribute values, and entities respectively. By utilizing these models, we can store and retrieve data in a flexible manner.</p><p>I hope you found this post to be helpful. If you would like to explore this example further and see a complete frontend and backend implementation, I encourage you to check out the following <a href="https://github.com/spotwilliams/eav-medium">repo</a>!</p><h4>Update</h4><p>I’ve realized that the subquery in the withCustomAttributes scope can be written using the query builder directly. Here&#39;s an updated version using the query builder instead of raw SQL statements:</p><pre>public function scopeWithCustomAttributes(Builder $query): void<br>{<br>    /** @var Collection&lt;CustomAttribute&gt; $attributes */<br>    $attributes = CustomAttribute::all();<br><br>    // Build the select list: the header of the query result will have the list of fields (ids) and the values will be located at the same level.<br>    // as result, we will have in one row all the values of the person.<br>    foreach ($attributes as $attribute) {<br>        $query-&gt;addSelect([<br>            // The key will append a new attribute on the resultant model with the name of the attribute<br>            $attribute-&gt;name =&gt; Value::query()<br>                // Only select the column that the attribute indicates<br>                -&gt;select($attribute-&gt;column_name)<br>                // Filter the attributes by person<br>                -&gt;whereColumn(&#39;values.person_id&#39;, &#39;=&#39;, &#39;people.id&#39;)<br>                // Only choose the attribute indicated here<br>                -&gt;where(&#39;values.custom_attribute_id&#39;, &#39;=&#39;, $attribute-&gt;id)<br>        ]);<br>    }<br>}</pre><p>I consider this an improvement because we’re using the PDO-dependent builder (which allows us to prevent attacks), and also, from a personal perspective, I think it looks better.</p><p>Finally, I’d like to mention that the App\Models\CustomAttribute class has a type attribute. We can utilize this attribute to instruct Eloquent to cast the dynamically added attributes to the resulting model.</p><pre>public function scopeWithCustomAttributes(Builder $query): void<br>{<br>    // ...<br>    foreach ($attributes as $attribute) {<br>          // add select code here<br><br>      $query-&gt;withCasts([$attribute-&gt;name =&gt; $attribute-&gt;type]);<br>    }<br>}</pre><p>I hope these updates can be more helpful, and if you have any comments or suggestions, please feel free to share them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a54e9f89240" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief story of how a bad composer constraint can make a release unuseful]]></title>
            <link>https://medium.com/@ricardovergarawork/a-brief-story-of-how-a-bad-composer-constraint-can-make-a-release-unuseful-f7a397698978?source=rss-c14896ebfe6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7a397698978</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[composer]]></category>
            <category><![CDATA[fork]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Spotwilliams]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 07:24:32 GMT</pubDate>
            <atom:updated>2023-04-10T07:24:32.724Z</atom:updated>
            <content:encoded><![CDATA[<p>(Using forks to fix/update 3rd party repositories)</p><p>The other day I was working on one project and I needed to use <a href="https://github.com/PHPOffice/PhpSpreadsheet">PHPOffice/PhpSpreadsheet</a> library in order to read and write xls files. After reviewing the README page on the library’s GitHub repository, I decided that it would be best to include it as a dependency in my project.</p><p>So, naturally as every normal human being, I opened a terminal on the root of my project and pasted this:</p><pre>composer require phpoffice/phpspreadsheet</pre><p>Have you ever experienced that feeling where you know that a simple task will require all your attention and effort? Well, that’s exactly how I felt that day. After waiting for just a moment, the terminal prompted me with the following message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6M_Cy0hLxGs_zsAeNAF-w.png" /><figcaption>console output</figcaption></figure><p>Is always hard (at least for me) read composer’s error messages. Too many numbers and symbols and in appearance all lines are the same. Anyway, after reading carefully I saw that PHPOffice/PhpSpreadsheet requires PHP7. Is that right? Well, naturally I double-checked the README file to see the versions compatibility and confirmed that actually the library it’s compatible. So, I keep reading the console to finally see this:</p><p>- phpoffice/phpspreadsheet[1.25.1, …, 1.28.0] <strong>require ezyang/htmlpurifier ^4.15</strong> -&gt; found ezyang/htmlpurifier[v4.15.0, v4.16.0] but the package is fixed to <strong>v4.13.0</strong></p><p>So, the root of the problem was a version compatibility issue with one of my previous dependencies. To solve this, the obvious solution was to update either the conflicting library or the related library.</p><p>In my case, mews/purifier was the library that needed to be updated, as it had ezyang/htmlpurifier as a dependency. After reviewing the GitHub repository for mews/purifierI found out that the latest version had the right version of <a href="https://github.com/ezyang/htmlpurifier">ezyang/htmlpurifier</a> that was compatible with both mews/purifier and PHPOffice/PhpSpreadsheet.</p><p>So, naturally I went again to my terminal and try to update mews/purifier:</p><pre>composer update mews/purifier</pre><p>To my surprise, when I attempted to update to the latest release of mews/purifier, I found that Composer was unable to do so. Despite the fact that the mews/purifier repository indicated that the latest tag was 3.3.9, my composer.lock file still pointed to version 3.3.8.</p><p>Initially, I thought that Composer’s cache might be causing the issue. So, I attempted to update using the -no-cache flag, but the situation persisted. To cover all possibilities, I choose to specify the version of mews/purifier directly in my composer.json file using the following code:</p><pre>&quot;require&quot;: {<br>    &quot;mews/purifier&quot;: &quot;^3.3.9&quot;<br>  }</pre><p>Things started to get really strange at this point, composer rejected the update saying:</p><blockquote>Root composer.json requires mews/purifier <strong>^3.3.9</strong>, found mews/purifier[dev-master-l4, 1.0.1, 1.0.2, 2.0.0, …, 2.1.4, 3.0.0, …, <strong>3.3.8</strong>] but it does not match the constraint.</blockquote><p>This error message seemed like nonsense to me. Why was Composer unable to see the real latest version of this package? Feeling a bit crazy, I decided to directly modify my composer.lock file and update the reference to version 3.3.9. I made the necessary changes to my composer.lock file, which now looked like this:</p><pre>{<br>    &quot;name&quot;: &quot;mews/purifier&quot;,<br>    &quot;version&quot;: &quot;3.3.9&quot;,<br>    &quot;source&quot;: {<br>        &quot;type&quot;: &quot;git&quot;,<br>        &quot;url&quot;: &quot;https://github.com/mewebstudio/Purifier.git&quot;,<br>        &quot;reference&quot;: &quot;e7523ae12d17de76057e625f971daa73b51beeee&quot;<br>    },<br>    &quot;dist&quot;: {<br>        &quot;type&quot;: &quot;zip&quot;,<br>        &quot;url&quot;: &quot;https://api.github.com/repos/mewebstudio/Purifier/zipball/e7523ae12d17de76057e625f971daa73b51beeee&quot;,<br>        &quot;reference&quot;: &quot;e7523ae12d17de76057e625f971daa73b51beeee&quot;,<br>        &quot;shasum&quot;: &quot;&quot;<br>    },<br>    &quot;require&quot;: {<br>      &quot;php&quot;: &quot;^7.2|^8.0&quot;,<br>      ...<br>      &quot;ezyang/htmlpurifier&quot;: &quot;^4.16.*&quot;<br>    },<br>    ...<br>},</pre><p>Essentially, what I was trying to do manually was what Composer typically handles for you. When you execute composer update, Composer copies the contents of your composer.json file and maintains references to the latest commits of each release.</p><p>After modifying my composer.lock file, I attempted to execute composer update once again. Can you believe what happened next?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*IyPJiiT8KteMLozmaq-oIQ.png" /></figure><p>And yet composer was again going against my request and using the previous version as before. So after attempting various creative and ridiculous solutions (like restart docker, the computer, and even practicing yoga) I figured out that problem was the way that one restriction was indicated in mews/purifier’s composer.json</p><pre>&quot;ezyang/htmlpurifier&quot;: &quot;^4.16.*&quot;</pre><p>It turned out that the issue was caused by an incorrect restriction in mews/purifier&#39;s composer.json file - the <strong>star at the end of the version</strong> was causing Composer to reject the release. Fortunately, the solution was relatively simple, just update the composer.json file. But now, I faced a new challenge - how to make this change immediately available to Composer and more important, to my project.</p><p>So, in order to accomplish that the best solution is to create a fork. By creating a fork, I was able to make the necessary changes to the composer.json file, push the changes to my fork, and then reference it in my own project&#39;s composer.json file. This allowed me to work around the issue and continue developing my project without any further issues.</p><p><strong>What’s a fork?</strong></p><blockquote>A fork is a new repository that shares code and visibility settings with the original “upstream” repository. <a href="https://docs.github.com/en/get-started/quickstart/fork-a-repo">(Github)</a></blockquote><p>Forking a repository is a way to create your own copy of someone else’s repository, make changes to it, and then potentially merge those changes back into the original repository.</p><p>So, in the context of my morning, I used the fork to make the next update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05skRw2vDHQ8uC0qlEzFCA.png" /></figure><p>With those changes committed to the forked repository, I waited for the pull request to be reviewed and merged by the maintainers of the original repository. However, my manager couldn’t afford to wait for the merge to happen and needed a quick solution to continue pushing code.</p><p>So, I decided to use the forked repository as a custom dependency in my project. To do that, I updated the composer.json file to include a new repository pointing to the forked repository, and then added the dependency with the modified version.</p><p>Here’s the updated composer.json file:</p><pre>{<br>    &quot;name&quot;: &quot;my-project&quot;,<br>    &quot;repositories&quot;: [<br>        {<br>            &quot;type&quot;: &quot;vcs&quot;,<br>            &quot;url&quot;: &quot;https://github.com/my-username/purifier&quot;<br>        }<br>    ],<br>    &quot;require&quot;: {<br>        &quot;phpoffice/phpspreadsheet&quot;: &quot;^1.19&quot;,<br>        &quot;mews/purifier&quot;: &quot;dev-master as 3.3.9&quot;<br>    }<br>}</pre><p>With these changes, Composer installed the forked version of mews/purifier, allowing me to continue working on the project without waiting for the merge to happen.</p><p>Once the pull request was finally merged and the new version of mews/purifier was available in the original repository, I simply updated the composer.json file to use the new version instead of the forked one.</p><p>I would like to express my gratitude to the owner of mews/purifier for promptly merging my changes and for their excellent work on the library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7a397698978" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How PHPStorm save my day]]></title>
            <link>https://medium.com/@ricardovergarawork/how-phpstorm-save-my-day-b3a93625e7ed?source=rss-c14896ebfe6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3a93625e7ed</guid>
            <category><![CDATA[phpstorm]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[ide]]></category>
            <dc:creator><![CDATA[Spotwilliams]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 19:12:26 GMT</pubDate>
            <atom:updated>2023-02-21T19:12:26.460Z</atom:updated>
            <content:encoded><![CDATA[<p>As a longtime user of PHPStorm, I often find myself tempted to switch to a free IDE like VSCode. However, every time I give it a shot, I end up coming back to PHPStorm. Recently, I was reminded why.</p><p>I was working on some feature tests for a project and realized I had an outdated SQL file I needed to update. This file contained thousands of insert lines, and I needed to remove a single column from each one (in my case, the last column of the insert clause). Initially, I thought I’d have to select lines in batches and manually delete the column or try to come up with a regular expression to do the job. But then I remembered a feature in PHPStorm that might help me out:</p><p>The SQL editor in PHPStorm has a nifty color background highlight helper that shows you what column are you working with. Once you identified, you can press <strong>Option and Enter</strong> to display ‘<strong>Show Context Actions</strong>’ (also can shake your mouse pointer and will see a light bubble).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jpeMPMja_h6_Cypko0y9bw.png" /></figure><p>One of the options that the IDE shows to me was exactly what I was looking for:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjKGQt70ogMf-YLrmEX14Q.png" /></figure><p>In my case, this saved me a ton of time and frustration. No more selecting lines in batches or struggling with regexes. Just a simple, efficient solution that made my job a lot easier. So if you’re a PHPStorm user and haven’t explored the SQL editor yet, I highly recommend giving it a try!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3a93625e7ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>