<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="/vendor/feed/atom.xsl" type="text/xsl"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-US">
                        <id>https://antoniojenaro.com/en/rss/blog</id>
                                <link href="https://antoniojenaro.com/en/rss/blog" rel="self"></link>
                                <title><![CDATA[Antonio Jenaro]]></title>
                    
                                <subtitle>El feed RSS para el blog de Antonio Jenaro que contiene artículos sobre Laravel, PHP y desarrollo web.</subtitle>
                                                    <updated>2024-12-23T08:00:00+01:00</updated>
                        <entry>
            <title><![CDATA[Generate Collections on the Fly with Laravel's times Method]]></title>
            <link rel="alternate" href="https://antoniojenaro.com/en/blog/generate-collections-on-the-fly-with-laravels-times-method" />
            <id>https://antoniojenaro.com/en/blog/generate-collections-on-the-fly-with-laravels-times-method</id>
            <author>
                <name><![CDATA[Antonio]]></name>
                <email><![CDATA[antonio.jenaro@gmail.com]]></email>

            </author>
            <summary type="html">
                <![CDATA[<img src="/storage/images/posts/dcTQdsRkcrcski26z1pXDrvVc5aR2BWX4UBUtDSy.jpg" alt="Generate Collections on the Fly with Laravel's times Method" /><p>Need to create a collection with calculated values? Laravel's times method lets you generate collections dynamically!</p><p><h3>#Basic Usage</h3>
<p>Here's the simplest way to use times:</p>
<p>&nbsp;</p>
<pre class="language-php"><code>$collection = Collection::times(10, function (int $number) {
    return $number * 9;
});
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]</code></pre>
<p>&nbsp;</p>
<h3>#Real-World Example</h3>
<p>Here's how you might use it in a date slot generator:</p>
<p>&nbsp;</p>
<pre class="language-php"><code>class AppointmentSlotGenerator
{
    public function generateDailySlots(
        string $startTime = '09:00',
        int $slotCount = 8,
        int $intervalMinutes = 60
    ) {
        return Collection::times($slotCount, function (int $index) use ($startTime, $intervalMinutes) {
            $time = Carbon::parse($startTime)
                -&gt;addMinutes(($index) * $intervalMinutes);
            
            return [
                'slot_id' =&gt; $index + 1,
                'start_time' =&gt; $time-&gt;format('H:i'),
                'end_time' =&gt; $time-&gt;addMinutes($intervalMinutes)-&gt;format('H:i'),
                'is_available' =&gt; true
            ];
        });
    }
}

// Usage
$generator = new AppointmentSlotGenerator();
$slots = $generator-&gt;generateDailySlots('10:00', 6, 30);

$slots-&gt;each(function ($slot) {
    $this-&gt;info("Slot {$slot['slot_id']}: {$slot['start_time']} - {$slot['end_time']}");
});</code></pre>
<p>&nbsp;</p>
<p>The&nbsp;<a href="https://laravel.com/docs/11.x/collections#method-times" target="_blank" rel="noopener"> times</a> method is perfect for generating sequences, creating test data, or any scenario where you need calculated values in a collection.</p></p>]]>
            </summary>
                                    <updated>2024-12-23T08:00:00+01:00</updated>
        </entry>
            <entry>
            <title><![CDATA[Securing File Uploads: Mastering File Type Validation in Laravel]]></title>
            <link rel="alternate" href="https://antoniojenaro.com/en/blog/securing-file-uploads-mastering-file-type-validation-in-laravel" />
            <id>https://antoniojenaro.com/en/blog/securing-file-uploads-mastering-file-type-validation-in-laravel</id>
            <author>
                <name><![CDATA[Antonio]]></name>
                <email><![CDATA[antonio.jenaro@gmail.com]]></email>

            </author>
            <summary type="html">
                <![CDATA[<img src="/storage/images/posts/xNW96O4GKWFLQKRlkJeR8sQo6XjRhBl9B4hqdPjn.jpg" alt="Securing File Uploads: Mastering File Type Validation in Laravel" /><p>In web applications, file uploads are a common feature, but they can also be a significant security risk if not handled properly. Laravel provides robust tools for validating file uploads, including the ability to verify file types. Let's explore how to implement secure file type validation in your Laravel applications.</p><p><h4><strong>#Understanding File Type Validation</strong></h4>
<p>&nbsp;</p>
<p>Laravel offers two primary methods for validating file types:</p>
<p>&nbsp;</p>
<ol>
<li>The mimes rule</li>
<li>
<p>The mimetypes rule</p>
<p>&nbsp;</p>
</li>
</ol>
<p>Both of these rules help ensure that uploaded files match expected types, but they work slightly differently.</p>
<p>&nbsp;</p>
<h4><strong>#Using the 'mimes' Rule</strong></h4>
<p>&nbsp;</p>
<p>The mimes rule validates files against a list of extension names:</p>
<p>&nbsp;</p>
<pre><code class="php-code">$request-&gt;validate([
    'document' =&gt; 'required|file|mimes:pdf,docx,txt|max:10240',
]);</code></pre>
<p>&nbsp;</p>
<p>In this example:</p>
<p>&nbsp;</p>
<ul>
<li>The file must be present (required)</li>
<li>It must be a file upload (file)</li>
<li>It must have an extension of pdf, docx, or txt</li>
<li>It must not exceed 10MB in size (10240 KB)</li>
</ul>
<p>&nbsp;</p>
<h4><strong>#Using the 'mimetypes' Rule</strong></h4>
<p>&nbsp;</p>
<p>The mimetypes rule checks the file's MIME type:</p>
<p>&nbsp;</p>
<pre><code class="php-code">$request-&gt;validate([
    'image' =&gt; 'required|file|mimetypes:image/jpeg,image/png|max:5120',
]);</code></pre>
<p>&nbsp;</p>
<p>This rule ensures:</p>
<p>&nbsp;</p>
<ul>
<li>The file is present</li>
<li>It's a file upload</li>
<li>It has a MIME type of either image/jpeg or image/png</li>
<li>It doesn't exceed 5MB in size</li>
</ul>
<p>&nbsp;</p>
<h4><strong>#Combining with Other Validation Rules</strong></h4>
<p>&nbsp;</p>
<p>You can combine these rules with other Laravel validation rules for comprehensive file validation:</p>
<p>&nbsp;</p>
<pre><code class="php-code">$request-&gt;validate([
    'avatar' =&gt; [
        'required',
        'file',
        'mimes:jpg,png',
        'dimensions:min_width=100,min_height=100',
        'max:2048',
    ],
]);</code></pre>
<p>&nbsp;</p>
<p>This example ensures the avatar is a jpg or png image, has minimum dimensions, and doesn't exceed 2MB.</p>
<p>&nbsp;</p>
<h4><strong>#Real-World Example: Document Management System</strong></h4>
<p>&nbsp;</p>
<p>Let's consider a more complex scenario for a document management system:</p>
<p>&nbsp;</p>
<pre><code class="php-code">public function store(Request $request)
{
    $request-&gt;validate([
        'document' =&gt; [
            'required',
            'file',
            'mimes:pdf,doc,docx,txt,xls,xlsx',
            'max:20480',  // 20MB max
        ],
        'document_type' =&gt; 'required|in:contract,report,presentation',
        'description' =&gt; 'required|string|max:500',
    ]);

    if ($request-&gt;document_type === 'presentation' &amp;&amp; !in_array($request-&gt;file('document')-&gt;extension(), ['ppt', 'pptx'])) {
        return back()-&gt;withErrors(['document' =&gt; 'Presentations must be PowerPoint files.']);
    }

    // Process and store the document
    $path = $request-&gt;file('document')-&gt;store('documents');

    Document::create([
        'path' =&gt; $path,
        'type' =&gt; $request-&gt;document_type,
        'description' =&gt; $request-&gt;description,
        'user_id' =&gt; auth()-&gt;id(),
    ]);

    return redirect()-&gt;route('documents.index')-&gt;with('success', 'Document uploaded successfully.');
}</code></pre>
<p>&nbsp;</p>
<p>This example demonstrates:</p>
<p>&nbsp;</p>
<ul>
<li>Basic file type and size validation</li>
<li>Additional contextual validation based on document type</li>
<li>Proper file storage and database recording</li>
</ul>
<p>&nbsp;</p>
<p>Validating file types is a crucial aspect of building secure Laravel applications that handle file uploads. By leveraging Laravel's built-in validation rules and combining them with custom logic, you can create robust and secure file handling systems. Always remember to validate on the server-side and never trust client-side validation alone. With these practices in place, you can confidently manage file uploads in your Laravel applications.</p></p>]]>
            </summary>
                                    <updated>2024-09-12T10:00:00+02:00</updated>
        </entry>
            <entry>
            <title><![CDATA[Simplifying Data Manipulation with Laravel's High Order Collections]]></title>
            <link rel="alternate" href="https://antoniojenaro.com/en/blog/simplifying-data-manipulation-with-laravels-high-order-collections" />
            <id>https://antoniojenaro.com/en/blog/simplifying-data-manipulation-with-laravels-high-order-collections</id>
            <author>
                <name><![CDATA[Antonio]]></name>
                <email><![CDATA[antonio.jenaro@gmail.com]]></email>

            </author>
            <summary type="html">
                <![CDATA[<img src="/storage/images/posts/HfghLQjxwpVo11tx2IiQ4M2TwknUw1cHU8STkKmu.jpg" alt="Simplifying Data Manipulation with Laravel's High Order Collections" /><p>Laravel's collections are already a powerful tool for working with arrays of data, but high order collections take this to the next level. These methods allow you to perform common operations on collections in a more concise and expressive way, leading to cleaner and more readable code. Let's dive into how you can leverage high order collections in your Laravel projects.</p><p><h4><strong>#Understanding High Order Collections</strong></h4><p>&nbsp;</p><p>High order collection methods in Laravel allow you to call collection methods directly on the collection items, without the need for nested closures. This results in more compact and often more readable code.</p><p>&nbsp;</p><h4><strong>#Basic Usage</strong></h4><p>&nbsp;</p><p>Here's a simple example comparing traditional collection methods with high order methods:</p><p>&nbsp;</p><pre><code class="php-code">// Traditional approach
$activeUserNames = $users-&gt;filter(function ($user) {
    return $user-&gt;isActive();
})-&gt;map(function ($user) {
    return $user-&gt;name;
});

// Using high order collections
$activeUserNames = $users-&gt;filter-&gt;isActive()-&gt;map-&gt;name;</code></pre><p>&nbsp;</p><p>As you can see, the high order approach is much more concise.</p><p>&nbsp;</p><h4><strong>#Common High Order Methods</strong></h4><p>&nbsp;</p><h3><strong>filter()</strong></h3><p>&nbsp;</p><p>The filter() method becomes particularly elegant with high order collections:</p><p>&nbsp;</p><pre><code class="php-code">$adults = $users-&gt;filter-&gt;isAdult();</code></pre><p>&nbsp;</p><p>This assumes your User model has an isAdult() method.</p><p>&nbsp;</p><h3><strong>map()</strong></h3><p>&nbsp;</p><p>map() is another method that benefits greatly from the high order approach:</p><p>&nbsp;</p><pre><code class="php-code">$userEmails = $users-&gt;map-&gt;email;</code></pre><p>&nbsp;</p><p>This is equivalent to $users-&gt;map(function ($user) { return $user-&gt;email; }).</p><p>&nbsp;</p><h3><strong>sort()</strong></h3><p>&nbsp;</p><p>Sorting can also be simplified:</p><p>&nbsp;</p><pre><code class="php-code">$sortedUsers = $users-&gt;sortBy-&gt;lastLoginAt;</code></pre><p>&nbsp;</p><h4><strong>#Chaining Multiple High Order Methods</strong></h4><p>One of the strengths of high order collections is the ability to chain multiple operations:</p><p>&nbsp;</p><pre><code class="php-code">$result = $users
    -&gt;filter-&gt;isActive()
    -&gt;map-&gt;name
    -&gt;sort()
    -&gt;take(5);</code></pre><p>&nbsp;</p><p>This code filters for active users, maps to their names, sorts the names, and takes the first 5.</p><p>&nbsp;</p><h4><strong>#Real-World Example: Processing Orders</strong></h4><p>&nbsp;</p><p>Let's look at a more complex example involving order processing:</p><p>&nbsp;</p><pre><code class="php-code">$highValueOrders = $orders
    -&gt;filter-&gt;isPaid()
    -&gt;filter-&gt;shipped()
    -&gt;map-&gt;items
    -&gt;collapse()
    -&gt;groupBy-&gt;product_id
    -&gt;map-&gt;sum('price')
    -&gt;filter(function ($total) {
        return $total &gt; 1000;
    })
    -&gt;sortDesc()
    -&gt;take(10);</code></pre><p>&nbsp;</p><p>This code does the following:</p><ul><li>Filters for paid and shipped orders</li><li>Maps to the items in each order</li><li>Collapses the items into a single collection</li><li>Groups items by product ID</li><li>Sums the price for each product</li><li>Filters for products with total sales over $1000</li><li>Sorts in descending order</li><li>Takes the top 10</li></ul><p>&nbsp;</p><h4><strong>#Combining with Regular Collection Methods</strong></h4><p>&nbsp;</p><p>High order methods can be seamlessly combined with regular collection methods:</p><p>&nbsp;</p><pre><code class="php-code">$result = $users
    -&gt;filter-&gt;isActive()
    -&gt;mapToGroups(function ($user) {
        return [$user-&gt;role =&gt; $user-&gt;name];
    })
    -&gt;map-&gt;sort()
    -&gt;map-&gt;take(3);</code></pre><p>&nbsp;</p><p>This groups active users by role, sorts names within each role, and takes the top 3 from each group.</p><p>&nbsp;</p><h4><strong>#Performance Considerations</strong></h4><p>&nbsp;</p><p>While high order collections can make your code more readable, be aware that they might have a slight performance overhead compared to using closures directly. For most applications, this difference is negligible, but it's worth considering for performance-critical sections of your code.</p></p>]]>
            </summary>
                                    <updated>2024-09-10T10:00:17+02:00</updated>
        </entry>
            <entry>
            <title><![CDATA[Automating Database Backups with Laravel's Task Scheduler and Cloud Storage]]></title>
            <link rel="alternate" href="https://antoniojenaro.com/en/blog/automating-database-backups-with-laravels-task-scheduler-and-cloud-storage" />
            <id>https://antoniojenaro.com/en/blog/automating-database-backups-with-laravels-task-scheduler-and-cloud-storage</id>
            <author>
                <name><![CDATA[Antonio]]></name>
                <email><![CDATA[antonio.jenaro@gmail.com]]></email>

            </author>
            <summary type="html">
                <![CDATA[<img src="/storage/images/posts/bSs0SeyqEriQpibIPK5qqF4ZZW5GThjaVnUR6yKg.jpg" alt="Automating Database Backups with Laravel's Task Scheduler and Cloud Storage" /><p>Ensuring regular database backups is crucial for any application. Laravel's Task Scheduler combined with cloud storage provides an efficient way to automate this process. Let's explore how to implement automated database backups using Laravel and store them in the cloud.</p><p><h4><strong>#Setting Up the Backup Command</strong></h4><p>&nbsp;</p><p>First, create a custom Artisan command for the backup process:</p><p>&nbsp;</p><pre><code class="php-code">php artisan make:command DatabaseBackup</code></pre><p>&nbsp;</p><p>In the newly created command file:</p><p>&nbsp;</p><pre><code class="php-code">namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class DatabaseBackup extends Command
{
    protected $signature = 'db:backup';
    protected $description = 'Backup the database to cloud storage';

    public function handle()
    {
        $filename = "backup-" . now()-&gt;format('Y-m-d') . ".sql";
        $path = storage_path("app/backup/{$filename}");

        // Create the backup
        $command = "mysqldump --user=" . env('DB_USERNAME') ." --password=" . env('DB_PASSWORD') 
            . " --host=" . env('DB_HOST') . " " . env('DB_DATABASE') 
            . "  &gt; " . $path;

        exec($command);

        // Upload to cloud storage (e.g., AWS S3)
        Storage::disk('s3')-&gt;put("backups/{$filename}", file_get_contents($path));
        unlink($path); // Remove local copy

        $this-&gt;info('Database backup uploaded to S3.');
    }
}</code></pre><p>&nbsp;</p><h4><strong>#Scheduling the Backup</strong></h4><p>&nbsp;</p><p>Schedule the backup command in app/Console/Kernel.php:</p><p>&nbsp;</p><pre><code class="php-code">protected function schedule(Schedule $schedule)
{
    $schedule-&gt;command('db:backup')-&gt;daily()-&gt;at('01:00');
}</code></pre><p>&nbsp;</p><p>This schedules the backup to run daily at 1:00 AM.</p><p>&nbsp;</p><h4><strong>#Cloud Storage Configuration</strong></h4><p>&nbsp;</p><p>Ensure your cloud storage is configured in config/filesystems.php:</p><p>&nbsp;</p><pre><code class="php-code">'s3' =&gt; [
    'driver' =&gt; 's3',
    'key' =&gt; env('AWS_ACCESS_KEY_ID'),
    'secret' =&gt; env('AWS_SECRET_ACCESS_KEY'),
    'region' =&gt; env('AWS_DEFAULT_REGION'),
    'bucket' =&gt; env('AWS_BUCKET'),
    'url' =&gt; env('AWS_URL'),
    'endpoint' =&gt; env('AWS_ENDPOINT'),
],</code></pre><p>&nbsp;</p><p>Don't forget to set the corresponding environment variables in your .env file.</p><p>&nbsp;</p><p>By implementing this setup, you ensure that your database is regularly backed up and securely stored in the cloud. This approach provides an extra layer of data protection and makes disaster recovery more manageable.</p><p>&nbsp;</p><p>Remember to test your backup process thoroughly and periodically verify the integrity of your backups to ensure they're valid and can be restored if needed.</p></p>]]>
            </summary>
                                    <updated>2024-08-21T15:34:18+02:00</updated>
        </entry>
            <entry>
            <title><![CDATA[Remove Duplicate Characters in Strings With Laravel]]></title>
            <link rel="alternate" href="https://antoniojenaro.com/en/blog/remove-duplicate-characters-in-strings-with-laravel" />
            <id>https://antoniojenaro.com/en/blog/remove-duplicate-characters-in-strings-with-laravel</id>
            <author>
                <name><![CDATA[Antonio]]></name>
                <email><![CDATA[antonio.jenaro@gmail.com]]></email>

            </author>
            <summary type="html">
                <![CDATA[<img src="/storage/images/posts/AgkhMfUAu9eJZ9W9EkzCwFn5QXL1jrHG7oFz8Dgh.jpg" alt="Remove Duplicate Characters in Strings With Laravel" /><p>The Laravel team released v11.20 this week, including a new collection method, a deduplicate string method, the ability to use Enums with AssertableJson, and more.</p><p><p>If you need to remove string duplication in Laravel and PHP applications, Laravel <a href="https://laravel-news.com/laravel-11-20-0">v11.20</a> adds a new method named <strong>deduplicate</strong> to the String helpers, which allows you to quickly and easily remove duplicate characters.</p><p>&nbsp;</p><pre><code class="php-code">use Illuminate\Support\{Str,Stringable};
 
$string = '/usr/local////path/to///desktop';
 
Str::deduplicate($string, '/');
// "/usr/local/path/to/desktop"
 
(new Stringable($string))-&gt;deduplicate('/')-&gt;toString();
// "/usr/local/path/to/desktop"</code></pre><p>&nbsp;</p><p>The default replacement character in the <strong>deduplicate()</strong> method is a space character, which could also be a use for the <strong>squish()</strong> helper introduced in <a href="https://laravel-news.com/laravel-9-7-0">Laravel v9.7.0</a>. Let me illustrate when <strong>squish()</strong> might be a better choice to remove extra spaces:</p><p>&nbsp;</p><pre><code class="php-code">Str::deduplicate(' John     Smith Jr.  '); // " John Smith Jr. "
Str::squish(' John     Smith Jr.  '); // "John Smith Jr."</code></pre><p>&nbsp;</p><p>Note the extra space <strong>' '</strong> characters at the beginning and end using <strong>deduplicate()</strong>, which is by design. Deduplicate is used to replace consecutive instances of a given character with a single character in the given string. Squish also removes other space characters, such as newlines and tabs:</p><p>&nbsp;</p><pre><code class="php-code">// Each example returns `laravel php framework`:
Str::squish(' laravel php framework '));
Str::squish("laravel\t\tphp\n\nframework");
Str::squish('
    laravel
    php
    framework
');</code></pre><p>&nbsp;</p></p>]]>
            </summary>
                                    <updated>2024-08-19T13:31:16+02:00</updated>
        </entry>
            <entry>
            <title><![CDATA[Upload Files Using Filepond in Livewire Components]]></title>
            <link rel="alternate" href="https://antoniojenaro.com/en/blog/upload-files-using-filepond-in-livewire-components" />
            <id>https://antoniojenaro.com/en/blog/upload-files-using-filepond-in-livewire-components</id>
            <author>
                <name><![CDATA[Antonio]]></name>
                <email><![CDATA[antonio.jenaro@gmail.com]]></email>

            </author>
            <summary type="html">
                <![CDATA[<img src="/storage/images/posts/nj0xBIV97I2DmYc3D4k1Hsz0uikj3ENNbIRk7FEr.jpg" alt="Upload Files Using Filepond in Livewire Components" /><p>Filepond is a JavaScript package that allows you to upload anything, with popular integrations for React, Vue, Svelte, and more</p><p><p>If you're using Livewire, now you can easily use Filepond to upload files within Livewire components using <a href="https://github.com/spatie/livewire-filepond">Spatie's livewire-filepond package</a>. This package contains a <a href="https://laravel-news.com/tag/livewire">Livewire</a> component that allows you to start using it in your Laravel projects easily:</p><p>&nbsp;</p><pre><code class="php-code">use LivewireComponent;
use SpatieLivewireFilepondWithFilePond;
 
class MyLivewireComponent extends Component
{
    use WithFilePond;
 
    public $file;
}
 
// &lt;x-filepond::upload wire:model="file" /&gt;</code></pre><p>&nbsp;</p><p>You can pass any property that Filepond accepts, and you can further customize the Livewire Filepond component with the following options available at the time of writing:</p><p>&nbsp;</p><ul><li>Allow multiple file uploads</li><li>Make the file upload required</li><li>Ability to disable the upload input</li><li>Custom placeholder text</li></ul><p>&nbsp;</p><p>You can learn more about this package, get full installation instructions, and view the <a href="https://github.com/spatie/livewire-filepond">source code</a> on GitHub. To learn more about this project, check out Freek Van der Herten's <a href="https://freek.dev/2738-a-package-to-use-filepond-in-your-livewire-component">writeup</a> about this package.</p></p>]]>
            </summary>
                                    <updated>2024-08-01T14:43:47+02:00</updated>
        </entry>
            <entry>
            <title><![CDATA[A Lightweight Cart Package for Laravel]]></title>
            <link rel="alternate" href="https://antoniojenaro.com/en/blog/a-lightweight-cart-package-for-laravel" />
            <id>https://antoniojenaro.com/en/blog/a-lightweight-cart-package-for-laravel</id>
            <author>
                <name><![CDATA[Antonio]]></name>
                <email><![CDATA[antonio.jenaro@gmail.com]]></email>

            </author>
            <summary type="html">
                <![CDATA[<img src="/storage/images/posts/fBCzbp3mlBnHxYXrZwjTjDQQ8JprLqmoQWfStiQp.jpg" alt="A Lightweight Cart Package for Laravel" /><p>The binafy/laravel-cart package adds the ability to add shopping cart functionality to Laravel applications. It simplifies storing and managing cart items, supports storing multiple item types, and more</p><p><h4>Features</h4><p>&nbsp;</p><ul><li>Secure card information storage and management</li><li>Support for multiple payment gateways</li><li>Recurring payment and subscription management</li><li>Robust validation and error handling</li><li>Highly customizable and flexible architecture</li></ul><p>&nbsp;</p><p>From the package's documentation, here's an example of retrieving a cart for a given user and adding an item to the cart:</p><p>&nbsp;</p><pre><code class="php-code">$cart = Cart::query()-&gt;firstOrCreate(['user_id' =&gt; $user-&gt;id]);
$cartItem = new CartItem([
    'itemable_id' =&gt; $itemable-&gt;id,
    'itemable_type' =&gt; $itemable::class,
    'quantity' =&gt; 1,
]);
 
$cart-&gt;items()-&gt;save($cartItem);
 
// Or create and store
Cart::query()-&gt;firstOrCreateWithStoreItems(
    item: $product,
    quantity: 1,
    userId: $user-&gt;id
);</code></pre><p>&nbsp;</p><p>This package also allows you to store multiple items in the cart, and the cart items are polymorphic model associations. You can access the underlying model associated with the <strong>CartItem</strong> using the <strong>itemable()</strong> method:</p><p>&nbsp;</p><pre><code class="php-code">$cartItem-&gt;itemable()-&gt;first();</code></pre><p>&nbsp;</p><p>Here you can see an <a href="https://antoniojenaro.com/en/laravel/examples/shopping-cart">example of how it works</a>.</p><p>&nbsp;</p><p>You can learn more about this package, get full installation instructions, and view the <a href="https://github.com/binafy/laravel-cart">source code</a> on GitHub.</p></p>]]>
            </summary>
                                    <updated>2024-07-01T00:25:20+02:00</updated>
        </entry>
            <entry>
            <title><![CDATA[Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4]]></title>
            <link rel="alternate" href="https://antoniojenaro.com/en/blog/create-a-datetime-from-a-timestamp-with-this-new-method-coming-to-php-84" />
            <id>https://antoniojenaro.com/en/blog/create-a-datetime-from-a-timestamp-with-this-new-method-coming-to-php-84</id>
            <author>
                <name><![CDATA[Antonio]]></name>
                <email><![CDATA[antonio.jenaro@gmail.com]]></email>

            </author>
            <summary type="html">
                <![CDATA[<img src="/storage/images/posts/AhCHXtanyBl0SEjEL6ib6s0YbA2QHATI0mHcwvlt.jpg" alt="Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4" /><p>Creating a DateTime from a Unix timestamp will be more convenient in PHP 8.4 with the new createFromTimestamp() method</p><p><p>It will support both a typical Unix timestamp as well as timestamps containing microseconds:</p><p>&nbsp;</p><pre><code class="php-code">$dt = DateTimeImmutable::createFromTimestamp(1718337072);
$dt-&gt;format('Y-m-d'); // 2024-06-14
 
$dt = DateTimeImmutable::createFromTimestamp(1718337072.432);
$dt-&gt;format('Y-m-d h:i:s.u'); // 2024-06-14 03:51:12.432000</code></pre><p>&nbsp;</p><p>With PHP 8.3 and below, you need to use the <strong>createFromFormat()</strong> method to convert a timestamp into a <strong>DateTime</strong> or <strong>DateTimeImmutable</strong> instance. As you can see below, it's not too complicated, but it'll be nice to have a new method to take care of both cases below:</p><p>&nbsp;</p><pre><code class="php-code">$dt = DateTimeImmutable::createFromFormat('U', (string) 1718337072);
// DateTimeImmutable @1718337072 {#7948
//   date: 2024-06-14 03:51:12.0 +00:00,
// }
 
$dt = DateTimeImmutable::createFromFormat('U.u', (string) 1718337072.432);
// DateTimeImmutable @1718337072 {#7950
//   date: 2024-06-14 03:51:12.432 +00:00,
// }</code></pre><p>&nbsp;</p><p>For those using the Carbon PHP library, it already has a <strong>createFromTimestamp()</strong> method available! It is encouraging that PHP is getting this new method at the language level as well!</p><p>&nbsp;</p><pre><code class="php-code">Carbon\Carbon::createFromTimestamp(1718337072.432);
// Carbon\Carbon @1718337072 {#7981
//   date: 2024-06-14 03:51:12.432 UTC (+00:00),
// }
 
Carbon\CarbonImmutable::createFromTimestamp(1718337072);
// Carbon\CarbonImmutable @1718337072 {#7999
//  date: 2024-06-14 03:51:12.0 UTC (+00:00),
// }</code></pre><p>&nbsp;</p></p>]]>
            </summary>
                                    <updated>2024-06-15T10:53:07+02:00</updated>
        </entry>
            <entry>
            <title><![CDATA[Randomize Command Execution Time with the Chaotic Schedule Package for Laravel]]></title>
            <link rel="alternate" href="https://antoniojenaro.com/en/blog/randomize-command-execution-time-with-the-chaotic-schedule-package-for-laravel" />
            <id>https://antoniojenaro.com/en/blog/randomize-command-execution-time-with-the-chaotic-schedule-package-for-laravel</id>
            <author>
                <name><![CDATA[Antonio]]></name>
                <email><![CDATA[antonio.jenaro@gmail.com]]></email>

            </author>
            <summary type="html">
                <![CDATA[<img src="/storage/images/posts/If8v5ah5D8kggTZzWmCKUkqjIn0dqXH8sIyot3Jp.jpg" alt="Randomize Command Execution Time with the Chaotic Schedule Package for Laravel" /><p>The chaotic-schedule package for Laravel allows you to randomize scheduled command execution time and date intervals via Pseudorandom number generators (PRNGs)</p><p><blockquote><p><i>"Ever wanted to run your scheduled commands on random times of the day, or on certain days of the week? Or you may need to send some notifications not on fixed date times, but rather on random intervals hence it feels more human. Then this is the package you're looking for.</i></p><p><i>This Laravel packages enables you to run commands on random intervals and periods while respecting the boundaries set exclusively by you".</i></p></blockquote><p>&nbsp;</p><p><i>One use-case mentioned in the readme is sending user notifications or emails but sending them randomly to add a more personal human touch. Avoiding the sending of these messages at regular intervals at the same time would be more recognizably automated:</i></p><p>&nbsp;</p><pre><code class="php-code">// Run a command daily on a random time between 08:15 and 11:42
$schedule-&gt;command('inspire')-&gt;daily()-&gt;atRandom('08:15','11:42');
 
// Run a command every Tuesday, Saturday and Sunday on a random time between 04:20 and 06:09
$schedule-&gt;command('your-command-signature:here')
    -&gt;days([Schedule::TUESDAY, Schedule::SATURDAY, Schedule::SUNDAY])
    -&gt;atRandom('04:20','06:09');</code></pre><p>&nbsp;</p><p>This package includes quite a few methods to define your random specifications based on several factors, such as:</p><p>&nbsp;</p><ul><li><strong>- dailyAtRandom()</strong></li><li><strong>- hourlyAtRandom()</strong></li><li><strong>- hourlyMultipleAtRandom()</strong></li><li><strong>- randomDays()</strong></li></ul><p>&nbsp;</p><p>You can learn more about this package, get full installation instructions, and view the <a href="https://github.com/skywarth/chaotic-schedule">source code on GitHub</a>.</p></p>]]>
            </summary>
                                    <updated>2024-06-10T15:25:46+02:00</updated>
        </entry>
            <entry>
            <title><![CDATA[Laravel Herd for Windows is now released]]></title>
            <link rel="alternate" href="https://antoniojenaro.com/en/blog/laravel-herd-for-windows-is-now-released" />
            <id>https://antoniojenaro.com/en/blog/laravel-herd-for-windows-is-now-released</id>
            <author>
                <name><![CDATA[Antonio]]></name>
                <email><![CDATA[antonio.jenaro@gmail.com]]></email>

            </author>
            <summary type="html">
                <![CDATA[<img src="/storage/images/posts/VW77Rqvh9yYrNiAgAKrORrBWe6iyqc6ozwcK25s8.jpg" alt="Laravel Herd for Windows is now released" /><p>Laravel Herd is a blazingly fast, native Laravel and PHP development environment. It’s now available for everyone running Windows machines. It includes everything you need to start Laravel development, including PHP and Nginx. Once you install Herd, you're ready to start developing with Laravel.</p><p><h2><strong>Herd Features Include</strong></h2><p>&nbsp;</p><p><strong>The fastest environment around</strong></p><p>Herd uses native binaries for PHP, nginx, and other services, making it faster than other PHP development environments. No containers, VMs, or wonky virtualization methods – just plain binaries as it should be.</p><p>Herd will install tools you need for development, like Composer, the Laravel installer, and more.</p><p>&nbsp;</p><p><strong>Everything you need to get started</strong></p><p>Herd includes binaries for Composer, the Laravel installer, and Expose, which are automatically available to your CLI.</p><p>This makes it possible to manage your sites via Powershell or use the Herd site wizard.</p><p>&nbsp;</p><p><strong>Unlock your real productivity</strong></p><p>Herd Pro comes with services for databases, caches, queues, storage, and realtime applications, changing how you work.</p><p>You can manage everything you ever need from one beautiful application.</p><p>&nbsp;</p><h2><strong>Download Herd For Windows</strong></h2><p><a href="https://herd.laravel.com/windows">Download the Windows version</a> and give it a try today.</p></p>]]>
            </summary>
                                    <updated>2024-05-27T08:00:00+02:00</updated>
        </entry>
            <entry>
            <title><![CDATA[How to check which version of Laravel I have installed in two seconds]]></title>
            <link rel="alternate" href="https://antoniojenaro.com/en/blog/how-to-check-which-version-of-laravel-i-have-installed-in-two-seconds" />
            <id>https://antoniojenaro.com/en/blog/how-to-check-which-version-of-laravel-i-have-installed-in-two-seconds</id>
            <author>
                <name><![CDATA[Antonio]]></name>
                <email><![CDATA[antonio.jenaro@gmail.com]]></email>

            </author>
            <summary type="html">
                <![CDATA[<img src="/storage/images/posts/cX2sJ6wspuDWVTXsI52jYPax8ZNGpGRu1A49AiuK.jpg" alt="How to check which version of Laravel I have installed in two seconds" /><p>Have you ever wanted to know what version of Laravel you have installed? Here I show you how to find out in two seconds.</p><p><p>Ever wanted to know what version of Laravel you have installed?</p>
<p>&nbsp;</p>
<p>Here's the quickest way to find out...</p>
<p>&nbsp;</p>
<p>Open your terminal and cd into your project then run:</p>
<p>&nbsp;</p>
<pre class="language-php"><code>php artisan about</code></pre>
<pre>&nbsp;</pre>
<p>&nbsp;</p>
<p>This will give you a complete list of all the details about your sites, including the version.</p>
<p>&nbsp;</p>
<pre class="language-php"><code>Environment ........................................
  Application Name ........................... Laravel
  Laravel Version ............................ 10.46.0
  PHP Version ................................. 8.2.13
  Composer Version ............................. 2.4.1
  Environment .................................. local
  Debug Mode ................................. ENABLED
  URL ..............................antoniojenaro.test
  Maintenance Mode ............................... OFF

  Cache ..............................................
  Config .................................. NOT CACHED
  Events .................................. NOT CACHED
  Routes .................................. NOT CACHED
  Views ....................................... CACHED

  Drivers ............................................
  Broadcasting ................................... log
  Cache ......................................... file
  Database ..................................... mysql
  Logs ................................ stack / single
  Mail .......................................... smtp
  Queue ......................................... sync
  Session ................................... database

  Livewire ...........................................
  Livewire .................................... v3.4.6</code></pre>
<pre>&nbsp;</pre></p>]]>
            </summary>
                                    <updated>2024-05-22T08:00:00+02:00</updated>
        </entry>
    </feed>
