<?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 MahmoudHadry on Medium]]></title>
        <description><![CDATA[Stories by MahmoudHadry on Medium]]></description>
        <link>https://medium.com/@mahmoudhadry?source=rss-9eac34f66a2b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oHNenn9TnVIv7A6jHTyX0A.jpeg</url>
            <title>Stories by MahmoudHadry on Medium</title>
            <link>https://medium.com/@mahmoudhadry?source=rss-9eac34f66a2b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:53:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahmoudhadry/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[10 Essential Laravel Excel File Handling Strategies Every Developer Should Master]]></title>
            <link>https://medium.com/@mahmoudhadry/10-essential-laravel-excel-file-handling-strategies-every-developer-should-master-80ef79775634?source=rss-9eac34f66a2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/80ef79775634</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[file-handling]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[maatwebsite]]></category>
            <dc:creator><![CDATA[MahmoudHadry]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 08:40:38 GMT</pubDate>
            <atom:updated>2025-04-27T08:40:38.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4oYSQLgwMi9vObkZnzUcLw.png" /></figure><p>Working with user-uploaded spreadsheets can be messy — but with the right tricks, Laravel Excel (Maatwebsite) makes it a breeze. In this article we’ll cover <strong>10 practical strategies</strong> for secure uploading, efficient processing, and solid reporting of Excel/CSV files in Laravel. Each point is a quick tip with example code, all based on the latest Laravel-Excel features. Ready? Let’s jump in!</p><h3>1. Validate and Secure Your Uploads</h3><p>First things first: <strong>never trust unvalidated files</strong>. Use Laravel’s validator to check the file type and size before you even try to parse it. For example, in your controller you might write:</p><pre>$request-&gt;validate([<br>    &#39;sheet&#39; =&gt; &#39;required|file|mimes:xls,xlsx,csv|max:2048&#39;,<br>]);</pre><p>This ensures only Excel/CSV files up to 2MB get through. You can also check file contents or scan for malware if needed. In short, always handle file uploads <strong>securely</strong> and reject anything suspicious​.</p><h3>2. Store the File (Don’t Process It Directly)</h3><p>Once validated, <strong>store the file on disk or S3</strong>. This isolates the raw upload and gives you a stable path to work with. For example:</p><pre>$path = $request-&gt;file(&#39;sheet&#39;)-&gt;store(&#39;imports&#39;);<br>// later...<br>Excel::import(new UsersImport, $path);</pre><p>Storing first also lets you queue or retry imports without losing the original file. It’s a small extra step that pays off (and avoids weird permission issues).</p><h3>3. Use Heading Rows and Mapped Columns</h3><p>If your spreadsheets have a header row, implement WithHeadingRow so you can refer to columns by name instead of index. For example:</p><pre>namespace App\Imports;<br>use App\User;<br>use Maatwebsite\Excel\Concerns\ToModel;<br>use Maatwebsite\Excel\Concerns\WithHeadingRow;<br><br>class UsersImport implements ToModel, WithHeadingRow {<br>    public function model(array $row) {<br>        return new User([<br>            &#39;name&#39; =&gt; $row[&#39;name&#39;],    // uses header &quot;Name&quot;<br>            &#39;email&#39;=&gt; $row[&#39;email&#39;],   // uses header &quot;Email&quot;<br>        ]);<br>    }<br>}</pre><p>This makes your code self-documenting and less error-prone. As the docs explain, a heading row lets you use the column names as array keys​</p><h3>4. Validate Data with WithValidation</h3><p>Don’t just trust that each cell is correct. Implement WithValidation in your import class to enforce Laravel-style rules on each row. For example:</p><pre>use Maatwebsite\Excel\Concerns\WithValidation;<br><br>class UsersImport implements ToModel, WithHeadingRow, WithValidation {<br>    public function rules(): array {<br>        return [<br>            &#39;email&#39;    =&gt; [&#39;required&#39;,&#39;email&#39;],   // header “Email” must be a valid email<br>            &#39;*.age&#39;    =&gt; [&#39;integer&#39;,&#39;min:0&#39;],    // any column “age” must be a non-negative integer<br>        ];<br>    }<br>}</pre><p>This way the import will automatically check each row against your rules. The library even throws a validation exception if something is wrong, so you can catch it and report errors. (The official docs note that WithValidation lets you “indicate the rules that each row need to adhere to”.)</p><h3>5. Handle Validation Failures Gracefully</h3><p>When validation fails, you have options. You can <strong>skip bad rows</strong> or <strong>gather errors for reporting</strong>. For instance, use the SkipsFailures trait to automatically skip invalid rows and collect all failures at the end:</p><pre>use Maatwebsite\Excel\Concerns\SkipsFailures;<br><br>class UsersImport implements ToModel, WithValidation, SkipsOnFailure {<br>    use SkipsFailures;<br>    // onFailure() can log or collect each issue as needed<br>}</pre><p>After the import finishes, you can inspect $import-&gt;failures() to see which rows failed. Alternatively, wrap the import in a try/catch and grab the failures from the exception:</p><pre>try {<br>    $import = new UsersImport();<br>    $import-&gt;import(&#39;users.xlsx&#39;);<br>} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {<br>    $failures = $e-&gt;failures(); <br>    // $failures is an array of Failure objects with row, errors, etc.<br>}</pre><p>The docs show exactly this pattern for collecting failures​. In short: skip or collect — but <strong>don’t just ignore invalid rows</strong>.</p><h3>6. Optimize Large Imports with Chunking (and Batch Inserts)</h3><p>If your file has thousands of rows, loading it all at once is a recipe for out-of-memory errors. Instead use <strong>chunk reading</strong> and <strong>batch inserts</strong>. For example:</p><pre>use Maatwebsite\Excel\Concerns\WithChunkReading;<br>use Maatwebsite\Excel\Concerns\WithBatchInserts;<br><br>class LargeImport implements ToModel, WithChunkReading, WithBatchInserts {<br>    public function chunkSize(): int {<br>        return 500;  // process 500 rows at a time<br>    }<br>    public function batchSize(): int {<br>        return 500;  // insert 500 models per query<br>    }<br>    public function model(array $row) {<br>        return new Record([ /* ... */ ]);<br>    }<br>}</pre><p>With this, Laravel Excel will read 500 rows into memory, insert them in one database query, then move to the next 500. This <strong>drastically reduces memory use and query count</strong>​. You may need to play with these numbers: the docs even warn that a chunk of 1000 “will not be the most optimal situation — play around to find the sweet spot”​<a href="https://docs.laravel-excel.com/3.1/imports/chunk-reading.html#:~:text=A%20chunk%20size%20of%20,to%20find%20the%20sweet%20spot">docs.laravel-excel.com</a>. (As an advanced trick, you could compute chunk size based on file size or available memory at runtime.)</p><h3>7. Use Queues for Heavy Lifting</h3><p>For very large imports, run them in the background with queues. Simply implement ShouldQueue on your import class <strong>alongside</strong> chunk reading:</p><pre>use Illuminate\Contracts\Queue\ShouldQueue;<br><br>class BigImport implements ToModel, WithChunkReading, ShouldQueue { /* ... */ }</pre><p>Then dispatch it:</p><pre>Excel::queueImport(new BigImport, &#39;big-data.xlsx&#39;);</pre><p>Each chunk will be a queued job. This means your HTTP request returns immediately and workers do the rest. According to the docs, “each chunk of 1000 rows will now be executed into a queue job” when you add ShouldQueue​. It’s a simple way to scale: Laravel handles retries and you keep your web server snappy.</p><h3>8. Hook into Import Events (Progress &amp; Custom Logic)</h3><p>Laravel Excel fires events during import (BeforeImport, AfterSheet, AfterImport, etc.). Use the WithEvents concern to listen and react. For example:</p><pre>use Maatwebsite\Excel\Concerns\WithEvents;<br>use Maatwebsite\Excel\Events\AfterImport;<br><br>class MyImport implements WithEvents {<br>    public function registerEvents(): array {<br>        return [<br>            AfterImport::class =&gt; function(AfterImport $event) {<br>                \Log::info(&#39;Excel import finished at &#39;.now());<br>            },<br>        ];<br>    }<br>}</pre><p>This gives you hooks to update a progress bar, notify users, or chain jobs after the import. The docs note that “the import process has a few events you can leverage” to add custom behavior​. You can also use RegistersEventListeners trait for simpler syntax. Either way, events let you get creative (e.g. update a status table or send a Slack message when done).</p><h3>9. Generate Reports or Feedback</h3><p>After importing, always give feedback. That might mean returning the number of imported rows, or emailing a report of any failures. For instance, you can loop over the failures and save them to a log or create a new Excel file of rejected rows. The library even lets you <strong>export</strong> arrays or models back to Excel for a summary. In code, after importing above, you could do:</p><pre>foreach ($import-&gt;failures() as $failure) {<br>    // e.g. log row number and error messages<br>    \Log::warning(&quot;Row {$failure-&gt;row()} failed: &quot;.implode(&#39;, &#39;, $failure-&gt;errors()));<br>}</pre><p>Or send this info in an email to the uploader. The key is to <strong>report what happened</strong> — don’t leave the user guessing if their upload worked. The docs show catching the ValidationException and iterating $e-&gt;failures() to inspect each bad row​. Use that data to build a clear status report.</p><h3>10. Miscellaneous Tips &amp; Advanced Tricks</h3><p>Finally, a few extra pointers:</p><ul><li><strong>Progress Bar:</strong> If running imports from Artisan, add the WithProgressBar concern to see a console. It’s great for long tasks.</li><li><strong>Multiple Sheets:</strong> Use the WithMultipleSheets concern if your Excel has several sheets to process.</li><li><strong>Memory Limits:</strong> For ultra-large exports, consider using Excel::store() instead of Excel::download() to write to disk, or use CSV/stream exports to save memory.</li><li><strong>Clean Up:</strong> After import, delete or archive the original file so you don’t fill up storage.</li><li><strong>Stay Updated:</strong> The Laravel-Excel docs and blog posts (like this one!) are frequently updated, so check for new features.</li></ul><p>Most of all, experiment with the settings above. The official docs emphasize tweaking chunk and batch sizes to find your “sweet spot”​.</p><blockquote><em>💪 </em><strong><em>Now go conquer those spreadsheets!</em></strong><em> You’ve learned to validate and upload safely, map and check your data, process it efficiently (with chunking, queues, etc.), and report results clearly. Put these strategies into practice, and Excel import/export will no longer be a headache — it’ll be just another routine task in your Laravel toolkit. Happy coding!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80ef79775634" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Unique & Powerful Laravel Microservices Strategies Most Developers Don’t Know (But Should!)]]></title>
            <link>https://medium.com/@mahmoudhadry/10-unique-powerful-laravel-microservices-strategies-most-developers-dont-know-but-should-9c3ec1660f9c?source=rss-9eac34f66a2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c3ec1660f9c</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[MahmoudHadry]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 09:48:08 GMT</pubDate>
            <atom:updated>2025-04-13T09:48:08.822Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6QzM8fJkQbZcswBtUcz7mQ.png" /></figure><p>Hey, Laravel devs!<br> You’ve mastered Eloquent, Blade, and queues — but have you tapped into the power of microservices? Breaking your monolith into focused services can supercharge scalability, resilience, and team productivity. Here are 10 unique Laravel microservices strategies you probably aren’t using yet (but absolutely should).</p><h3>1. Define Clear Service Boundaries (Save Your Sanity!)</h3><p>Don’t let your services bleed into one another. Start with Domain‑Driven Design (DDD) to identify bounded contexts — User Management, Product Catalog, Order Processing, etc. — and give each its own repo and database.</p><pre>// In ProductService: product-service/src/Contracts/ProductRepository.php<br>namespace App\Contracts;<br><br>interface ProductRepository {<br>    public function find(int $id): Product;<br>    public function search(array $filters): Collection;<br>}</pre><p>✅ Perfect for: Teams working in parallel without stepping on each other’s toes.</p><h3>2. Choose the Right Framework: Lumen vs. Full Laravel</h3><ul><li><strong>Lumen</strong>: Blazing‑fast, minimal dependencies — ideal for simple CRUD or stateless APIs.</li><li><strong>Laravel</strong>: Full‑featured — use when you need middleware, events, or rich tooling (Eloquent, Policies, Queues).</li></ul><pre># Lumen for lightweight auth service<br>composer create-project --prefer-dist laravel/lumen auth-service</pre><p>🚀 Pro tip: Start with Lumen, then “upgrade” to Laravel if your service grows.</p><h3>3. Use an API Gateway for Centralized Routing &amp; Auth</h3><p>Implement a single entry point that handles authentication, rate limiting, and request aggregation.</p><pre>// api-gateway/routes/web.php<br>Route::middleware(&#39;auth:api&#39;)-&gt;group(function () {<br>    Route::get(&#39;/users/{id}&#39;, fn($id) =&gt; Http::get(&quot;http://user-service/users/{$id}&quot;));<br>    Route::post(&#39;/orders&#39;, fn() =&gt; Http::post(&#39;http://order-service/orders&#39;, request()-&gt;all()));<br>});</pre><p>✅ Perfect for: Enforcing global policies and hiding internal topology.</p><h3>4. Embrace Asynchronous Communication with Queues</h3><p>Avoid tight coupling with sync HTTP calls — publish events instead!</p><pre>// In OrderService when an order is placed<br>event(new OrderCreated($order));<br><br>// In PaymentService listener<br>public function handle(OrderCreated $event) {<br>    // process payment...<br>}</pre><p>Use Redis, RabbitMQ, or Amazon SQS for your broker.<br> 🔔 Pro tip: Laravel’s ShouldQueue interface makes listeners auto‑queued.</p><h3>5. Standardize Service Contracts with OpenAPI/Swagger</h3><p>Keep everyone on the same page — literally. Define your API schemas in YAML/JSON and generate client SDKs.</p><pre># api-gateway/openapi.yaml<br>paths:<br>  /products:<br>    get:<br>      summary: List products<br>      responses:<br>        &#39;200&#39;:<br>          description: OK<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/Product&#39;</pre><p>✅ Perfect for: Ensuring backward‑compatible changes and auto‑generating docs.</p><h3>6. Leverage Docker &amp; Docker Compose for Local Dev</h3><p>Spin up all services — and dependencies — in one command.</p><pre># docker-compose.yml<br>version: &#39;3.8&#39;<br>services:<br>  api-gateway: { build: ./api-gateway, ports: [&quot;8000:8000&quot;] }<br>  user-service: { build: ./user-service, ports: [&quot;8001:8000&quot;] }<br>  rabbitmq:    { image: rabbitmq:3-management, ports: [&quot;5672:5672&quot;,&quot;15672:15672&quot;] }</pre><p>🚀 Pro tip: Use named networks to let services talk by container name (e.g., <a href="http://user-service:8000).">http://user-service:8000).</a></p><h3>7. Implement Service Discovery &amp; Centralized Config</h3><p>Avoid hard‑coding URLs — use Consul, Eureka, or DNS‑based discovery. Centralize secrets and configs with Vault or AWS Parameter Store.</p><pre># In each service .env<br>SERVICE_DISCOVERY_URL=http://consul:8500</pre><p>🔒 Pro tip: Rotate credentials without redeploying services.</p><h3>8. Secure Services with JWT &amp; Middleware</h3><p>Issue JWTs at the gateway, then validate them in each service via middleware.</p><pre>// In each service’s Kernel.php<br>protected $routeMiddleware = [<br>    &#39;jwt.auth&#39; =&gt; \App\Http\Middleware\AuthenticateJwt::class,<br>];</pre><p>✅ Perfect for: Zero‑trust architecture and stateless auth.</p><h3>10. Automate CI/CD for Each Service</h3><p>Treat each microservice like its own deployable unit. Use GitHub Actions, GitLab CI, or Jenkins pipelines to run tests, build Docker images, and deploy.</p><pre># .github/workflows/ci.yml<br>on: [push]<br>jobs:<br>  build-and-test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v2<br>      - run: composer install --no-interaction<br>      - run: php artisan test<br>      - run: docker build -t myorg/user-service .</pre><p>✅ Perfect for: Catching regressions early and ensuring consistent releases.</p><h3>BONUS: Sample E‑Commerce Microservices Demo</h3><h3>Docker Compose Snippet</h3><pre>version: &#39;3.8&#39;<br>services:<br>  api-gateway:     { build: ./api-gateway, ports: [&quot;8000:8000&quot;] }<br>  user-service:    { build: ./user-service, ports: [&quot;8001:8000&quot;] }<br>  product-service: { build: ./product-service, ports: [&quot;8002:8000&quot;] }<br>  order-service:   { build: ./order-service, ports: [&quot;8003:8000&quot;] }<br>  rabbitmq:        { image: rabbitmq:3-management, ports: [&quot;5672:5672&quot;,&quot;15672:15672&quot;] }</pre><h3>User Service (Lumen) Example</h3><pre>composer create-project --prefer-dist laravel/lumen user-service</pre><pre>// routes/web.php<br>$router-&gt;get(&#39;/users/{id}&#39;, &#39;UserController@show&#39;);<br><br>// app/Http/Controllers/UserController.php<br>namespace App\Http\Controllers;<br>use App\Models\User;<br>class UserController extends Controller {<br>    public function show($id) {<br>        return response()-&gt;json(User::findOrFail($id));<br>    }<br>}</pre><pre>// app/Http/Controllers/OrderController.php<br>use App\Events\OrderCreated;<br>public function store(Request $req) {<br>    $order = Order::create($req-&gt;all());<br>    event(new OrderCreated($order));<br>    return response()-&gt;json($order, 201);<br>}</pre><h3>Final Thoughts</h3><p>Microservices can transform your Laravel applications — boosting scalability, resilience, and team velocity. Which strategy will you implement first? Got a hidden gem we missed? Drop a comment below!</p><p>Want expert help architecting your next microservices project? Reach out to our team for hands‑on guidance and best practices.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c3ec1660f9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>