<?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 Ahmed Ebead on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Ebead on Medium]]></description>
        <link>https://medium.com/@ahmedm3bead?source=rss-7bad226600ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*i7oo-KsiG1lgpEAodD3N_w.jpeg</url>
            <title>Stories by Ahmed Ebead on Medium</title>
            <link>https://medium.com/@ahmedm3bead?source=rss-7bad226600ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:23:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmedm3bead/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[Building Focus Flow: An AI Skill That Speaks English, Formal Arabic, and Egyptian Arabic]]></title>
            <link>https://medium.com/@ahmedm3bead/building-focus-flow-an-ai-skill-that-speaks-english-formal-arabic-and-egyptian-arabic-1d46d8f4b840?source=rss-7bad226600ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d46d8f4b840</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ahmed Ebead]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 09:23:43 GMT</pubDate>
            <atom:updated>2026-09-13T09:23:43.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_CwFwiOjkX8Dr2sBrbUH5g.png" /></figure><h3>Building Focus Flow: An AI Skill That Speaks English, Formal Arabic, and Egyptian Arabic</h3><p>AI assistants often give correct answers that are harder to execute than they need to be.</p><p>The answer may start with a long introduction, introduce several side topics, provide too many options, and end without making the next action obvious.</p><p>I built <strong>Focus Flow</strong> to solve this problem.</p><p>Focus Flow is an open-source AI skill that shapes responses around clarity, execution, and reduced cognitive friction. It works in English and Arabic, including both Modern Standard Arabic and Egyptian Arabic.</p><p>GitHub repository:</p><p><a href="https://github.com/ahmed3bead/focus-flow">https://github.com/ahmed3bead/focus-flow</a></p><h3>The problem</h3><p>A technically correct answer is not always an actionable answer.</p><p>Consider a developer asking why an API request returns a 401 response. A typical AI answer may explain authentication, middleware, token validation, configuration, dependencies, and several possible causes before identifying what the developer should check first.</p><p>Focus Flow changes the response structure.</p><p>Instead of burying the action, it leads with it:</p><blockquote><em>Check whether the request contains the </em><em>Authorization header, then rerun the failing test.</em></blockquote><p>Context and explanation can still follow, but the user immediately knows where to start.</p><h3>What Focus Flow changes</h3><p>Focus Flow applies ten core response principles:</p><ol><li>Lead with the answer or next action.</li><li>Number tasks only when sequence matters.</li><li>Keep one clear next action visible.</li><li>Suppress unrelated tangents.</li><li>Preserve progress across conversation turns.</li><li>Use concrete time estimates when they are useful.</li><li>Make completed work visible.</li><li>Report errors using location, cause, fix, and verification.</li><li>Limit the visible working set.</li><li>Remove introductions, recaps, and closing filler.</li></ol><p>These rules are defaults, not absolute restrictions.</p><p>If the user requests a detailed explanation, the assistant should explain fully. Safety checks still take priority, destructive actions still require confirmation, and technical correctness must never be sacrificed for brevity.</p><h3>Arabic is not just a translation</h3><p>The main addition in Focus Flow is its language and register policy.</p><p>The skill can respond in:</p><ul><li>English</li><li>Modern Standard Arabic</li><li>Egyptian Arabic</li><li>Mixed Arabic and English for technical conversations</li></ul><p>The user does not need to configure a language manually.</p><p>Focus Flow examines the current message and conversation style. Formal Arabic receives a clear Modern Standard Arabic response, while conversational Egyptian Arabic receives a natural Egyptian response.</p><p>For example, a message containing expressions such as:</p><blockquote><em>عاوز أعرف أبدأ منين ومش عاوز خطوات كتير</em></blockquote><p>should receive an Egyptian Arabic response.</p><p>A message such as:</p><blockquote><em>أريد شرح الفرق بين المصادقة والتفويض</em></blockquote><p>should receive a Modern Standard Arabic response.</p><p>The skill considers several language signals together instead of relying on a single keyword. It also avoids exaggerated slang and does not reproduce spelling mistakes to imitate the user.</p><p>Technical identifiers remain unchanged. Filenames, commands, API names, framework names, and error messages are preserved when translating them would reduce clarity.</p><h3>Installing Focus Flow in Codex</h3><p>Run:</p><pre>codex plugin marketplace add ahmed3bead/focus-flow --ref main<br>codex plugin add focus-flow@focus-flow</pre><p>Start a new conversation and activate the skill:</p><pre>$focus-flow</pre><p>Verify the installation with:</p><pre>codex plugin list</pre><h3>Installing Focus Flow in Claude Code</h3><p>Run:</p><pre>claude plugin marketplace add ahmed3bead/focus-flow<br>claude plugin install focus-flow@focus-flow</pre><p>Restart Claude Code and activate the skill:</p><pre>/focus-flow</pre><p>Verify the installation with:</p><pre>claude plugin list</pre><h3>Testing the Arabic behavior</h3><p>After activating Focus Flow, try this Egyptian Arabic prompt:</p><pre>أنا محتار بين كذا حاجة ومش عارف أبدأ منين. ساعدني أختار أول خطوة.</pre><p>The response should:</p><ul><li>Use natural Egyptian Arabic.</li><li>Start with one clear action.</li><li>Keep the visible choices limited.</li><li>Avoid unnecessary side topics.</li></ul><p>Then try a formal Arabic prompt:</p><pre>اشرح لي الفرق بين المصادقة والتفويض بطريقة تساعدني على التطبيق.</pre><p>The response should switch to Modern Standard Arabic while preserving the same focus-friendly structure.</p><h3>Testing and safety</h3><p>Focus Flow includes behavioral cases covering:</p><ul><li>Egyptian Arabic</li><li>Modern Standard Arabic</li><li>English</li><li>Mixed technical language</li><li>Explicit language overrides</li><li>Destructive operations</li><li>Detailed explanation requests</li><li>Session activation and deactivation</li></ul><p>The project also makes an important distinction: Focus Flow is an output style, not an ADHD diagnosis or medical tool.</p><h3>Open source</h3><p>Focus Flow is available under the MIT License.</p><p>The project was inspired by the open-source i-have-adhd project by Ayoub G., but Focus Flow has its own identity, wording, bilingual language policy, and Arabic-focused tests.</p><p>Contributions, testing, bug reports, and language feedback are welcome:</p><p><a href="https://github.com/ahmed3bead/focus-flow">https://github.com/ahmed3bead/focus-flow</a></p><p>If you try it in Arabic, I would especially like to know whether the switch between Modern Standard Arabic and Egyptian Arabic feels natural.</p><p>Suggested Medium tags:</p><p>Artificial Intelligence · Open Source · Arabic · Productivity · Software Development</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d46d8f4b840" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Polluting Your Services with Logging Code: Meet laravel-hooks]]></title>
            <link>https://medium.com/@ahmedm3bead/stop-polluting-your-services-with-logging-code-meet-laravel-hooks-065d06965a82?source=rss-7bad226600ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/065d06965a82</guid>
            <dc:creator><![CDATA[Ahmed Ebead]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 21:10:26 GMT</pubDate>
            <atom:updated>2026-04-16T21:10:26.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aMLiAPJnpRJhPRgFMtYITA.png" /></figure><p>Every order you create needs to be audited. Every payment needs a log line. Every user update needs to fire a webhook. You know the drill — and you know what happens: your clean OrderService::create() slowly grows a tail of AuditLog::create(...), Log::info(...), and dispatch(new NotifyAdmin(...)) calls that have nothing to do with creating an order.</p><p>I’ve been writing Laravel for a decade and I’ve watched this pattern rot half a dozen codebases, including my own. So I built a package to fix it.</p><h3>The old way</h3><p>You’ve got two mainstream options in Laravel, and both have sharp edges.</p><p><strong>Events and listeners</strong> work, but the ceremony is real. You define an event class, define a listener class, register the mapping in EventServiceProvider, then dispatch the event from inside your service. For one audit log line, that&#39;s four files and three mental jumps. Worse, once you&#39;ve dispatched an event you&#39;ve lost the return value and the exception context — if you want the created model <em>and</em> the thrown error, you&#39;re passing both into the event payload manually.</p><p><strong>Observers</strong> are cleaner, but they only work on Eloquent models. The moment you want to hook PaymentService::charge() or ProcessOrderJob::handle(), observers are out. And model events are coupled to the model lifecycle, not to <em>your</em> domain action — created fires on any insert, including the ones you didn&#39;t mean to audit (seeders, factories, imports).</p><p>Both approaches push cross-cutting concerns into the wrong places, or force you to build your own lightweight hook system inline. I’ve written that lightweight system maybe fifteen times. I got tired of it.</p><h3>Introducing laravel-hooks</h3><p>laravel-hooks adds before, after, and error lifecycle hooks to <strong>any method in any class</strong> — services, controllers, jobs, models, plain PHP objects, it doesn&#39;t care. You drop a trait on the class, wrap the method body in executeWithHooks(), and attach hooks from inside the class, from a service provider, or inline from anywhere that has a reference to the object. Hooks can run synchronously, on a queue, after a delay, in batches, or conditionally based on environment and config.</p><p>Install:</p><pre>composer require ahmedebead/laravel-hooks</pre><p>Laravel auto-discovers the provider. If you want to tweak the config:</p><pre>php artisan vendor:publish --tag=laravel-hooks-config</pre><p>Requirements: PHP 8.2+, Laravel 10–13.</p><h3>A real example: auditing order creation</h3><p>Here’s the service. Notice that the audit logic is nowhere in it.</p><pre>use Ahmed3bead\LaravelHooks\HookableTrait;<br><br>class OrderService<br>{<br>    use HookableTrait;<br>    public function create(array $data): Order<br>    {<br>        return $this-&gt;executeWithHooks(&#39;create&#39;, function () use ($data) {<br>            return Order::create($data);<br>        }, $data);<br>    }<br>    protected function registerHooks(): void<br>    {<br>        $this-&gt;afterHook(&#39;create&#39;, OrderCreatedHook::class);<br>    }<br>}</pre><p>registerHooks() is called automatically the first time the class uses a hook. No provider wiring needed for this case.</p><p>Now the hook class — this is where the audit actually happens:</p><pre>use Ahmed3bead\LaravelHooks\BaseHookJob;<br>use Ahmed3bead\LaravelHooks\HookContext;<br><br>class OrderCreatedHook extends BaseHookJob<br>{<br>    public function handle(HookContext $context): void<br>    {<br>        $order = $context-&gt;getModelFromResult();<br>        AuditLog::create([<br>            &#39;action&#39;   =&gt; &#39;order.created&#39;,<br>            &#39;order_id&#39; =&gt; $order?-&gt;id,<br>            &#39;user_id&#39;  =&gt; $context-&gt;getUserId(),<br>        ]);<br>    }<br>}</pre><p>Ten lines. No event class, no listener mapping, no observer boilerplate. The HookContext object gives you the method name, the phase (before/after/error), the authenticated user, the raw result, and a handful of helpers like getModelFromResult() that pull an Eloquent model out of whatever your method returned — works with plain models or wrapped API responses.</p><p>If the method throws, the error phase fires, your hook runs with the exception available on the context, and the exception is re-thrown. You don&#39;t swallow anything by accident.</p><h3>More power, same simple surface</h3><h3>Inline closures — skip the class entirely</h3><p>Not every hook deserves its own file. For quick additions, register a closure:</p><pre>$this-&gt;syncHookWithLogic(&#39;after&#39;, &#39;create&#39;, function (HookContext $ctx) {<br>    Log::info(&#39;Order created&#39;, [<br>        &#39;user_id&#39; =&gt; $ctx-&gt;getUserId(),<br>        &#39;order&#39;   =&gt; $ctx-&gt;getModelFromResult()?-&gt;id,<br>    ]);<br>});</pre><h3>Queued hooks — push heavy work off the request</h3><p>The audit log probably needs to be synchronous. A welcome email does not. Change one argument:</p><pre>$this-&gt;hook(&#39;after&#39;, &#39;create&#39;, SendWelcomeEmail::class, strategy: &#39;queue&#39;);</pre><p>Or inline:</p><pre>$this-&gt;hookWithLogic(&#39;after&#39;, &#39;create&#39;, function (HookContext $ctx) {<br>    dispatch(new SendWelcomeEmail($ctx-&gt;getUserId()));<br>}, strategy: &#39;queue&#39;);</pre><h3>Conditional hooks — only in production, only when a flag is on</h3><p>This is the one I use most. You want full audit logging in production but not in local dev, and you want it gated behind a config flag so you can kill it fast:</p><pre>use Ahmed3bead\LaravelHooks\HookManager;<br>use Ahmed3bead\LaravelHooks\Strategies\ConditionalHookStrategy;<br>use Ahmed3bead\LaravelHooks\Strategies\SyncHookStrategy;<br><br>$hooks = app(HookManager::class);<br>$strategy = (new ConditionalHookStrategy(new SyncHookStrategy()))<br>    -&gt;onlyInEnvironment(&#39;production&#39;)<br>    -&gt;onlyWhenConfigEnabled(&#39;features.audit&#39;);<br>$hooks-&gt;registerStrategy(&#39;prod_audit&#39;, $strategy);<br>$hooks-&gt;addHook(OrderService::class, &#39;create&#39;, &#39;after&#39;, OrderCreatedHook::class, &#39;prod_audit&#39;);</pre><p>Delayed and batched strategies are there too — addDelayedHook() schedules the hook for N seconds later (useful for follow-up emails), and addBatchedHook() collects executions and flushes them together (useful for analytics where you don&#39;t want 10,000 individual queue jobs).</p><h3>It works everywhere, not just in services</h3><p>The trait doesn’t care what class it’s on. Drop it on a controller to audit specific actions:</p><pre>class OrderController<br>{<br>    use HookableTrait;<br><br>    public function store(StoreOrderRequest $request)<br>    {<br>        return $this-&gt;executeWithHooks(&#39;store&#39;, function () use ($request) {<br>            return OrderResource::make($this-&gt;service-&gt;create($request-&gt;validated()));<br>        });<br>    }<br>}</pre><p>Drop it on a job to track background processing:</p><pre>class ProcessOrderJob implements ShouldQueue<br>{<br>    use HookableTrait, Queueable;<br><br>    public function handle(): void<br>        {<br>            $this-&gt;executeWithHooks(&#39;handle&#39;, function () {<br>                // ...<br>            });<br>        }<br>}</pre><p>Drop it on a model to observe domain methods (not Eloquent events — your own methods):</p><pre>class User extends Model<br>{<br>    use HookableTrait;<br><br>    public function promoteToAdmin(): void<br>      {<br>          $this-&gt;executeWithHooks(&#39;promoteToAdmin&#39;, function () {<br>              $this-&gt;role = &#39;admin&#39;;<br>              $this-&gt;save();<br>          });<br>      }<br>}</pre><p>That last one is the case observers can’t cover cleanly. promoteToAdmin fires only when <em>you</em> call it — not on every save — and your audit hook runs with full context about who did what.</p><h3>A few things worth knowing</h3><p><strong>Priority.</strong> Lower runs first, default is 100. Validation hooks at priority 10, notifications at 200, everything else in between.</p><p><strong>Global hooks.</strong> $hooks-&gt;addGlobalHook(&#39;create&#39;, &#39;after&#39;, GlobalAuditHook::class) fires for every class using the trait. Useful for blanket audit or debug logging across a whole app.</p><p><strong>Artisan commands.</strong> php artisan make:hook OrderCreated --type=audit --phase=after --sync scaffolds a hook class. php artisan hooks:manage list shows every registered hook; hooks:manage debug --target=... shows the ones attached to a specific class. You can enable, disable, clear, flush pending batches, and export the registry to JSON.</p><p><strong>Testing.</strong> Queue::fake() followed by Queue::assertPushed(QueuedHookJob::class) is enough to verify your queued hooks dispatched without actually running them.</p><h3>Give it a try</h3><pre>composer require ahmedebead/laravel-hooks</pre><p>Source, full API reference, and issues: <a href="https://github.com/ahmed3bead/laravel-hooks"><strong>github.com/ahmed3bead/laravel-hooks</strong></a></p><p>If you’ve been writing ad-hoc hook systems inside your services for years like I was — stop. Use this one, file issues when it annoys you, and let’s make the one tool that handles this properly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=065d06965a82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable Audit Logging for Multi-Tenant Laravel Applications: Tracking Every Action with Precision]]></title>
            <link>https://medium.com/@ahmedm3bead/scalable-audit-logging-for-multi-tenant-laravel-applications-tracking-every-action-with-precision-8d95b83abd16?source=rss-7bad226600ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d95b83abd16</guid>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[package]]></category>
            <category><![CDATA[audit]]></category>
            <dc:creator><![CDATA[Ahmed Ebead]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 21:05:52 GMT</pubDate>
            <atom:updated>2026-04-13T21:05:52.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Ne09MfYxom3zfvvXy2LAw.png" /></figure><h3>Introduction</h3><p>In the architecture of a modern multi-tenant SaaS, the audit log is often the unsung hero of the infrastructure. It serves as the definitive record for compliance, security forensics, and customer support. However, developers frequently hit a wall when using general-purpose auditing packages in a multi-tenant context. The most common issue is the “single-user assumption” — the idea that every action is performed by a single User model. In reality, SaaS platforms often juggle multiple actor types: platform admins, organization owners, vendors, and end customers, often residing in different database tables.</p><p>Generic packages also tend to lack a first-class tenant_id column. Without native tenant awareness, you are forced to perform expensive joins or complex filtering logic just to show a tenant their own activity history. Furthermore, these packages often focus exclusively on Eloquent lifecycle events like created or updated. While CRUD tracking is essential, it misses the high-level business logic that matters most—actions like &quot;Report Exported,&quot; &quot;Subscription Upgraded,&quot; or &quot;Access Impersonated.&quot;</p><p>That is why I developed ahmed3bead/laravel-tenant-audit. This package was built to bridge the gap between standard model auditing and the complex requirements of multi-tenancy. It provides a single-table solution that is morph-map aware, supports polymorphic actors without ID collisions, and treats the tenant as a primary citizen in every log entry. By the end of this article, you’ll see how to implement a bulletproof audit trail in your Laravel 10, 11, 12, or 13 application with minimal overhead.</p><h3>Installation &amp; Setup</h3><p>The package is designed to be lightweight and easy to integrate. You can install it via Composer:</p><pre>composer require ahmed3bead/laravel-tenant-audit</pre><p>Once installed, you need to publish the configuration and the migration files. The package uses tags to keep your config and database directories clean.</p><pre># Publish the configuration<br>php artisan vendor:publish --tag=tenant-audit-config<br><br># Publish and run migrations<br>php artisan vendor:publish --tag=tenant-audit-migrations<br>php artisan migrate</pre><p>The config/tenant-audit.php file is the heart of the package. Key options include tenant_resolver, which defines how the package finds the current tenant, and user_resolver, which identifies the actor. You can also toggle global settings like capture_ip and capture_user_agent to comply with local privacy laws like GDPR.</p><h3>Basic Usage</h3><p>To start auditing a model, you simply need to implement the AuditableContract and use the Auditable trait. This combination hooks into Laravel&#39;s model events automatically.</p><pre>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Model;<br>use Ahmed3bead\TenantAudit\Concerns\Auditable;<br>use Ahmed3bead\TenantAudit\Contracts\AuditableContract;<br>class Order extends Model implements AuditableContract<br>{<br>    use Auditable;<br>}</pre><p>Once this is in place, any created, updated, deleted, or restored action on the Order model triggers an entry in the tenant_audit_logs table. To view these logs, the trait provides a convenient auditLogs() relationship:</p><pre>$order = Order::find(1);<br>$history = $order-&gt;auditLogs()-&gt;latestFirst()-&gt;get();<br>foreach ($history as $log) {<br>    echo &quot;Event: {$log-&gt;event} | By: {$log-&gt;user-&gt;name}&quot;;<br>}</pre><h3>Attribute Filtering</h3><p>In a production environment, logging everything is often as bad as logging nothing. You don’t want to store password hashes, and you likely don’t care if a last_login_at timestamp was updated.</p><p>The package provides two layers of filtering: the $auditable allowlist and the $auditExclude excludelist. If $auditable is defined, the package ignores the excludelist and <strong>only</strong> logs the fields you’ve specified.</p><pre>class Order extends Model implements AuditableContract<br>{<br>    use Auditable;<br>    // Allowlist: Only track changes to status and total<br>    protected array $auditable = [&#39;status&#39;, &#39;total&#39;];<br>    // Excludelist: Even if $auditable wasn&#39;t set, never log internal notes<br>    protected array $auditExclude = [&#39;internal_notes&#39;];<br>}</pre><p>This ensures that if a user changes their password, internal notes, and order status in one request, only the status change is persisted to the audit log, keeping your database clean and your data secure.</p><h3>Multiple Actor Types</h3><p>One of the biggest hurdles in multi-tenant apps is distinguishing between different types of users. If an Admin with ID 1 and a Customer with ID 1 both perform actions, a simple user_id column creates a collision.</p><p>laravel-tenant-audit uses a polymorphic pair: user_type and user_id. You can configure how these are resolved in the config file. This is perfect for multi-guard setups:</p><pre>// config/tenant-audit.php<br>&#39;user_resolver&#39; =&gt; fn () =&gt; match (true) {<br>    auth(&#39;admin&#39;)-&gt;check()    =&gt; [&#39;type&#39; =&gt; \App\Models\Admin::class,    &#39;id&#39; =&gt; auth(&#39;admin&#39;)-&gt;id()],<br>    auth(&#39;vendor&#39;)-&gt;check()   =&gt; [&#39;type&#39; =&gt; \App\Models\Vendor::class,   &#39;id&#39; =&gt; auth(&#39;vendor&#39;)-&gt;id()],<br>    auth(&#39;customer&#39;)-&gt;check() =&gt; [&#39;type&#39; =&gt; \App\Models\Customer::class, &#39;id&#39; =&gt; auth(&#39;customer&#39;)-&gt;id()],<br>    default                   =&gt; null,<br>},</pre><p>Because the package is morph-map aware, if you have defined Relation::morphMap([&#39;admin&#39; =&gt; Admin::class]), the database will store the string admin instead of the full class path. When you access $log-&gt;user, Laravel will automatically return the correct Eloquent model instance.</p><h3>Custom Business Events</h3><p>CRUD operations don’t always tell the whole story. Sometimes you need to log an action that isn’t a simple database change. You can trigger custom events directly from your model instance or via a Facade.</p><p><strong>Using the Model:</strong></p><pre>$order-&gt;auditEvent(&#39;approved&#39;, <br>    metadata: [&#39;compliance_officer&#39; =&gt; &#39;Sarah Doe&#39;]<br>);</pre><p><strong>Using the Facade:</strong></p><pre>use Ahmed3bead\TenantAudit\Facades\TenantAudit;<br><br>TenantAudit::log(&#39;exported&#39;, $report, metadata: [&#39;format&#39; =&gt; &#39;pdf&#39;]);</pre><p>To prevent “event bloat,” you can enable strict mode in your configuration by adding allowed events to the custom_events array. If an event is triggered that isn&#39;t in that list, the package will ignore it, ensuring your logs remain consistent and searchable.</p><h3>Runtime Control</h3><p>There are scenarios where you want to perform operations silently — such as data migrations, automated syncing, or bulk updates — without flooding the audit table.</p><p>You can suppress auditing for a specific instance or an entire block of code:</p><pre>// Option 1: Disable on a specific instance<br>$order-&gt;disableAudit()-&gt;update([&#39;sync_status&#39; =&gt; &#39;completed&#39;]);<br><br>// Option 2: Wrap a block of code<br>Order::withoutAudit(function () {<br>    // None of these actions will be logged<br>    Order::where(&#39;status&#39;, &#39;old&#39;)-&gt;update([&#39;status&#39; =&gt; &#39;archived&#39;]);<br>});</pre><p>The withoutAudit method is particularly robust; it uses a try...finally block internally. This guarantees that even if your code throws an exception, the auditing state is restored, preventing accidental &quot;silent periods&quot; for the rest of the request.</p><h3>Querying Logs</h3><p>The package includes a dedicated AuditLog model equipped with several useful scopes. This makes building a &quot;Recent Activity&quot; dashboard for your tenants incredibly simple.</p><pre>use Ahmed3bead\TenantAudit\Models\AuditLog;<br><br>// Get everything for a specific tenant<br>$logs = AuditLog::forTenant(&#39;acme_corp&#39;)<br>    -&gt;latestFirst()<br>    -&gt;paginate(20);<br>// Filter by a specific actor<br>$adminLogs = AuditLog::forUser($adminModel)-&gt;get();<br>// Filter by a specific model and event<br>$specificLogs = AuditLog::forModel(Order::class, $orderId)<br>    -&gt;byEvent(&#39;approved&#39;)<br>    -&gt;get();</pre><p>By leveraging these scopes, you avoid writing complex JSON queries and keep your controller logic readable and maintainable.</p><h3>Advanced Config</h3><p>For high-scale applications, writing to the database synchronously can be a bottleneck. The package supports <strong>Async Queuing</strong> out of the box. Simply toggle queue =&gt; true in the config, and the audit logs will be processed by your queue workers, keeping your web responses snappy.</p><p>To prevent your tenant_audit_logs table from growing indefinitely, the package implements Laravel&#39;s MassPrunable trait. You can set prune_after_days =&gt; 90 in your config and schedule the built-in Laravel command:</p><pre>// routes/console.php<br>Schedule::command(&#39;model:prune&#39;, [<br>    &#39;--model&#39; =&gt; [Ahmed3bead\TenantAudit\Models\AuditLog::class],<br>])-&gt;daily();</pre><p>Finally, if you need to add custom methods or relationships to the audit logs, you can swap the default AuditLog model with your own class in the configuration file.</p><h3>Closing</h3><p>Providing a transparent audit trail shouldn’t be a secondary thought in multi-tenant development. With ahmed3bead/laravel-tenant-audit, you get a robust, flexible, and tenant-aware logging system that handles the edge cases—like multiple actor types and custom business events—right out of the box.</p><p>By centralizing your logs into a single, well-indexed table with automatic pruning and queue support, you ensure your application remains performant and compliant as it scales.</p><p><strong>GitHub:</strong> <a href="https://github.com/ahmed3bead/laravel-tenant-audit">https://github.com/ahmed3bead/laravel-tenant-audit</a></p><p>If you have ideas for new features or find a bug, please feel free to open an issue or submit a pull request. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d95b83abd16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Config Files: Managing Dynamic Settings in Laravel 13]]></title>
            <link>https://medium.com/@ahmedm3bead/beyond-config-files-managing-dynamic-settings-in-laravel-13-835a7cf6c0ad?source=rss-7bad226600ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/835a7cf6c0ad</guid>
            <dc:creator><![CDATA[Ahmed Ebead]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 00:44:54 GMT</pubDate>
            <atom:updated>2026-04-02T00:44:54.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTvZqVyFpK7DNjHcG5pt6w.png" /></figure><h3>The Problem: Static Configs in a Dynamic World</h3><p>Laravel’s config() system is great for values that change between <em>environments</em> (like API keys), but it’s terrible for values that change during <em>runtime</em> or vary by <em>user</em>.</p><p>If you’ve ever found yourself creating a user_preferences table just to store a &quot;dark_mode&quot; boolean, or adding a column to your accounts table for a &quot;timezone&quot; string, you’re creating technical debt. Your database schema shouldn&#39;t have to change every time you add a new toggle to your UI.</p><h3>Introducing: Laravel Settings</h3><p>I built <a href="https://github.com/ahmed3bead/laravel-settings"><strong>Laravel Settings</strong></a> to provide a professional, enterprise-ready way to handle dynamic data. It allows you to store settings globally, or scope them to any Eloquent model, all while maintaining strict type safety.</p><h3>Why This Matters for Laravel 13</h3><p>With the release of <strong>Laravel 13</strong>, the framework is leaning harder into PHP 8.3+ features, type safety, and better performance. This package is built to align with those standards, offering native support for the latest Laravel versions and ensuring your settings layer is as fast as the rest of your stack.</p><h3>Key Features that Solve Real Problems</h3><h3>1. Model Scoping (No More Messy Tables)</h3><p>Instead of adding endless columns to your User or Tenant models, you can attach settings dynamically:</p><pre>// Set a preference for a specific user<br>Settings::for($user)-&gt;set(&#39;dashboard_layout&#39;, &#39;compact&#39;);<br>// Retrieve it anywhere in your app<br>$layout = Settings::for($user)-&gt;get(&#39;dashboard_layout&#39;, &#39;default&#39;);</pre><h3>2. Automatic Type-Casting</h3><p>One of the most annoying parts of custom settings tables is that everything is stored as a string. With this package, <strong>types are preserved</strong>. If you store a Carbon date, a Boolean, or a complex Array, you get that exact type back.</p><pre>Settings::set(&#39;maintenance_mode_until&#39;, Carbon::now()-&gt;addHours(2));<br><br>// On retrieval, this is already a Carbon instance!<br>$time = Settings::get(&#39;maintenance_mode_until&#39;);</pre><h3>3. High-Performance Caching</h3><p>Database queries are expensive. <strong>Laravel Settings</strong> comes with built-in caching that automatically invalidates. When you update a setting, the cache for that specific key (and that specific model/group) is cleared instantly. It’s “set it and forget it” performance.</p><h3>Level Up with the HasSettings Trait</h3><p>To make things even cleaner, you can add a simple trait to your models:</p><pre>use Ahmed3bead\Settings\HasSettings;<br><br>class User extends Model {<br>    use HasSettings;<br>}<br>// Now you can do this:<br>$user-&gt;settings()-&gt;set(&#39;theme&#39;, &#39;midnight&#39;);</pre><h3>Conclusion: Build for the Future</h3><p>As we move into the era of <strong>Laravel 13</strong>, our applications need to be more flexible and modular than ever. By decoupling your application settings from your primary database schema, you make your code easier to test, faster to iterate on, and much cleaner to read.</p><p>I’d love to see how you use this in your projects!</p><p>📦 <strong>Packagist:</strong> <a href="https://packagist.org/packages/ahmedebead/laravel-settings">ahmedebead/laravel-settings</a> <br>💻 <strong>GitHub:</strong> <a href="https://github.com/ahmed3bead/laravel-settings">ahmed3bead/laravel-settings</a></p><p>#Laravel #PHP #WebDevelopment #Coding #Laravel13 #SoftwareArchitecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=835a7cf6c0ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing Boilerplate: Introducing Lara-CRUD for Enterprise Laravel Applications]]></title>
            <link>https://medium.com/@ahmedm3bead/stop-writing-boilerplate-introducing-lara-crud-for-enterprise-laravel-applications-875f88d785da?source=rss-7bad226600ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/875f88d785da</guid>
            <dc:creator><![CDATA[Ahmed Ebead]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 21:41:56 GMT</pubDate>
            <atom:updated>2026-04-01T21:42:41.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klHA33fV5w7jDxx4Q018iQ.png" /></figure><h3>The Developer’s Dilemma</h3><p>Every time we start a new feature in Laravel, we follow the same ritual: create a Model, a Migration, a Controller, a Request for validation, and maybe a Resource for the API. If you’re following clean architecture, you also add Repositories, Services, and DTOs.</p><p>By the time you finish the boilerplate, half your morning is gone. I built <strong>Lara-CRUD</strong> to solve exactly this — without sacrificing code quality or architectural integrity.</p><h3>What is Lara-CRUD?</h3><p>Lara-CRUD isn’t just another CRUD generator. While most tools stop at the Controller, Lara-CRUD builds a full <strong>Enterprise-Level Stack</strong>. It organizes your code into a modular structure that is easy to maintain and scale.</p><p>When you run php artisan lara-crud:go, it generates:</p><ul><li><strong>Services &amp; Repositories:</strong> For clean business logic and data access.</li><li><strong>DTOs &amp; Mappers:</strong> To keep your data structured and typed.</li><li><strong>API Resources &amp; Requests:</strong> For standardized responses and validation.</li><li><strong>UI Views:</strong> Support for <strong>Bootstrap</strong> and <strong>AdminLTE</strong> out of the box.</li></ul><h3>The Secret Sauce: The Service Hook System</h3><p>The most powerful feature of this package is the <strong>Service Hook System</strong>. In enterprise apps, “creating a record” is rarely just a database insert. You need to clear cache, send emails, notify Slack, or update search indexes.</p><p>Lara-CRUD allows you to hook into the lifecycle of your service methods:</p><ol><li><strong>Before Hooks:</strong> Perfect for extra validation or authorization.</li><li><strong>Core Logic:</strong> Your main business execution.</li><li><strong>After Hooks:</strong> Asynchronous execution for notifications or logging.</li></ol><p>This turns your standard CRUD into a highly flexible, event-driven architecture.</p><h3>Getting Started in 3 Steps</h3><h3>1. Installation</h3><pre>composer require ahmedebead/lara-crud</pre><h3>2. Generate Your Stack</h3><p>Run the magic command and follow the prompts for your table name:</p><pre>php artisan lara-crud:go</pre><h3>3. (Optional) Choose Your UI</h3><p>Want a dashboard? Just add the view flag:</p><pre>php artisan lara-crud:go --with-views=adminlte</pre><h3>Conclusion</h3><p>As developers, our time is best spent solving unique business problems, not writing repetitive code. <strong>Lara-CRUD</strong> handles the “boring” parts so you can focus on the “brave” parts of your application.</p><p>I’d love for you to try it out, star the repo, and let me know how it fits into your workflow!</p><p>📦 <strong>Packagist:</strong> <a href="https://packagist.org/packages/ahmedebead/lara-crud">ahmedebead/lara-crud</a> <br>💻 <strong>GitHub:</strong> <a href="https://github.com/ahmed3bead/lara-crud">ahmed3bead/lara-crud</a></p><p>#Laravel #PHP #WebDevelopment #OpenSource #CleanArchitecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=875f88d785da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Laravel on Google Cloud Platform: The Complete Production Guide]]></title>
            <link>https://medium.com/@ahmedm3bead/deploying-laravel-on-google-cloud-platform-the-complete-production-guide-22f1dfade6ae?source=rss-7bad226600ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/22f1dfade6ae</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Ahmed Ebead]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 14:57:16 GMT</pubDate>
            <atom:updated>2025-11-13T14:57:16.755Z</atom:updated>
            <content:encoded><![CDATA[<h3>From zero to fully-scaled serverless Laravel application using Cloud Run, Cloud SQL, Redis, and Cloud Storage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hfozbeuEDpibIhaft2hv_A.jpeg" /></figure><p><strong>Reading time:</strong> 25 minutes | <strong>Level:</strong> Intermediate to Advanced | <strong>Last updated:</strong> November 2025</p><h3>Introduction</h3><p>Deploying a Laravel application in production can be challenging. Should you use traditional VPS servers? Kubernetes? What about database scaling, file storage, and queue processing? After deploying dozens of Laravel applications on various platforms, I’ve found that <strong>Google Cloud Platform (GCP) offers one of the most elegant, scalable, and cost-effective solutions</strong> for modern Laravel deployments.</p><p>In this comprehensive guide, I’ll walk you through deploying a production-ready Laravel application using:</p><ul><li><strong>Cloud Run</strong> — Serverless containers that scale automatically</li><li><strong>Cloud SQL</strong> — Managed MySQL database with automatic backups</li><li><strong>Redis (Memorystore)</strong> — Blazing-fast caching and queue management</li><li><strong>Cloud Storage</strong> — Scalable file storage with global CDN</li><li><strong>Secret Manager</strong> — Secure secrets management</li><li><strong>VPC Networking</strong> — Private, secure communication between services</li></ul><p>By the end of this guide, you’ll have a <strong>professional infrastructure that handles thousands of users</strong>, scales automatically, and costs a fraction of traditional hosting.</p><h3>Why Google Cloud Platform for Laravel?</h3><p>Before we dive in, let’s address the elephant in the room: <strong>Why not AWS or Azure?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kpgjNKLEQMPUGgXQW2mOw.jpeg" /></figure><h3>GCP Advantages for Laravel</h3><p><strong>1. True Serverless with Cloud Run</strong> Unlike AWS Lambda’s 15-minute timeout, Cloud Run gives you up to 60 minutes of execution time and 32GB of RAM. Perfect for Laravel’s long-running processes.</p><p><strong>2. Simpler Pricing Model</strong> No surprise bills. You pay only for what you use, and the pricing is more predictable than AWS.</p><p><strong>3. Better Developer Experience</strong> GCP’s console is cleaner, and their CLI (gcloud) is more intuitive than AWS&#39;s CLI.</p><p><strong>4. Excellent Global Infrastructure</strong> With 40+ regions worldwide including <strong>Saudi Arabia (Dammam)</strong>, you can deploy close to your users for minimal latency.</p><p><strong>5. Superior Integration</strong> All GCP services integrate seamlessly. No need for complex IAM policies across 50+ services.</p><h3>Real Cost Comparison</h3><p>For a medium-traffic Laravel app (100K monthly users):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*VxAC4xh3IUkeRRCkXAdDMA.png" /></figure><h3>Architecture Overview</h3><p>Here’s what we’re building:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vT4vJ4U4KEqyP7ef8VZjhQ.jpeg" /></figure><p><strong>Key Components:</strong></p><ol><li><strong>Cloud Run</strong> — Runs your Laravel application in containers</li><li><strong>Cloud SQL</strong> — MySQL 8.0 database with automatic backups</li><li><strong>Redis (Memorystore)</strong> — For caching and Laravel queues</li><li><strong>Cloud Storage</strong> — User uploads and static files</li><li><strong>VPC Network</strong> — All services communicate privately</li><li><strong>Secret Manager</strong> — Stores passwords and API keys securely</li></ol><h3>Part 1: Prerequisites &amp; Initial Setup</h3><h3>What You’ll Need</h3><p>Before starting, ensure you have:</p><ul><li>✅ Google Cloud account (<a href="https://cloud.google.com/free">free $300 credit for new users</a>)</li><li>✅ Laravel application (Laravel 9, 10, or 11)</li><li>✅ Basic understanding of Docker</li><li>✅ gcloud CLI installed (<a href="https://cloud.google.com/sdk/docs/install">installation guide</a>)</li><li>✅ Git repository (GitHub, GitLab, or Bitbucket)</li></ul><h3>Create Your GCP Projects</h3><p><strong>Pro tip:</strong> Always separate staging and production environments.</p><pre># Create staging project<br>gcloud projects create connect-backend-stage \<br>  --name=&quot;Connect Backend - Staging&quot;<br><br># Create production project<br>gcloud projects create connect-backend-prod \<br>  --name=&quot;Connect Backend - Production&quot;<br># Set default project<br>gcloud config set project connect-backend-prod</pre><h3>Enable Required APIs</h3><pre>gcloud services enable \<br>  run.googleapis.com \<br>  sqladmin.googleapis.com \<br>  redis.googleapis.com \<br>  vpcaccess.googleapis.com \<br>  secretmanager.googleapis.com \<br>  storage.googleapis.com \<br>  cloudscheduler.googleapis.com</pre><p>This takes 2–3 minutes. Grab a coffee ☕</p><h3>Part 2: Setting Up the Database (Cloud SQL)</h3><p>Cloud SQL is GCP’s fully-managed relational database service. It handles backups, replication, patches, and scaling automatically.</p><h3>Why Cloud SQL Over Self-Managed MySQL?</h3><ul><li><strong>Automated backups</strong> — Daily backups with point-in-time recovery</li><li><strong>High availability</strong> — 99.95% SLA with automatic failover</li><li><strong>Security</strong> — Encrypted at rest and in transit</li><li><strong>Scaling</strong> — Vertical scaling in seconds (no downtime)</li><li><strong>Maintenance</strong> — Automatic security patches</li></ul><h3>Create VPC Network</h3><p>First, let’s create a private network for secure communication:</p><pre># Create VPC<br>gcloud compute networks create connect-vpc \<br>  --subnet-mode=custom<br><br># Create subnet in Saudi Arabia region<br>gcloud compute networks subnets create connect-subnet \<br>  --network=connect-vpc \<br>  --region=me-central2 \<br>  --range=10.0.0.0/24</pre><h3>Create Cloud SQL Instance</h3><p><strong>For Production:</strong></p><pre>gcloud sql instances create connect-db-prod \<br>  --database-version=MYSQL_8_0 \<br>  --tier=db-custom-4-16384 \<br>  --region=me-central2 \<br>  --network=projects/connect-backend-prod/global/networks/connect-vpc \<br>  --no-assign-ip \<br>  --database-flags=character_set_server=utf8mb4,collation_server=utf8mb4_unicode_ci \<br>  --backup-start-time=03:00 \<br>  --maintenance-window-day=SUN \<br>  --maintenance-window-hour=4 \<br>  --enable-bin-log \<br>  --retained-backups-count=30 \<br>  --deletion-protection \<br>  --availability-type=REGIONAL</pre><p><strong>What these flags mean:</strong></p><ul><li>--tier=db-custom-4-16384 — 4 vCPUs, 16GB RAM (adjust based on your needs)</li><li>--no-assign-ip — No public IP = more secure</li><li>--network — Connect to our private VPC</li><li>--backup-start-time=03:00 — Daily backups at 3 AM</li><li>--availability-type=REGIONAL — High availability with automatic failover</li></ul><p><strong>Staging environment</strong> — use smaller instance:</p><pre># Same command, but with:<br>--tier=db-custom-2-8192 \<br>--retained-backups-count=7</pre><h3>Configure Database</h3><p><strong>Generate secure password:</strong></p><pre>openssl rand -base64 32<br># Output: K8xP2mNv9QwR5tYuI3oL7aS6dF4gH1jZ0cV8bN2m=</pre><p><strong>🔒 Save this password immediately!</strong> You’ll need it multiple times.</p><p><strong>Set root password:</strong></p><pre>gcloud sql users set-password root \<br>  --instance=connect-db-prod \<br>  --password=&#39;YOUR_GENERATED_PASSWORD&#39;</pre><p><strong>Create Laravel user:</strong></p><pre>gcloud sql users create laravel-user \<br>  --instance=connect-db-prod \<br>  --password=&#39;YOUR_GENERATED_PASSWORD&#39;</pre><p><strong>Create database:</strong></p><pre>gcloud sql databases create laravel_db \<br>  --instance=connect-db-prod \<br>  --charset=utf8mb4 \<br>  --collation=utf8mb4_unicode_ci</pre><h3>Store Password in Secret Manager</h3><pre>echo -n &#39;YOUR_GENERATED_PASSWORD&#39; | \<br>  gcloud secrets create db-password \<br>    --replication-policy=automatic \<br>    --data-file=-</pre><h3>Part 3: Setting Up Redis (Memorystore)</h3><p>Redis is essential for Laravel’s caching and queue system. Memorystore is GCP’s managed Redis service.</p><h3>Create Redis Instance</h3><p><strong>Production (High Availability):</strong></p><pre>gcloud redis instances create connect-redis \<br>  --size=5 \<br>  --region=me-central2 \<br>  --redis-version=redis_7_0 \<br>  --network=projects/connect-backend-prod/global/networks/connect-vpc \<br>  --connect-mode=PRIVATE_SERVICE_ACCESS \<br>  --tier=standard-ha \<br>  --replica-count=1</pre><p><strong>Features:</strong></p><ul><li><strong>5GB memory</strong> — Sufficient for 100K+ sessions</li><li><strong>HA mode</strong> — Automatic failover if primary fails</li><li><strong>Redis 7.0</strong> — Latest stable version</li><li><strong>Private access</strong> — Only accessible from your VPC</li></ul><p><strong>Get Redis IP address:</strong></p><pre>gcloud redis instances describe connect-redis \<br>  --region=me-central2 \<br>  --format=&quot;value(host)&quot;<br># Output: 10.0.0.5</pre><p>Save this IP — you’ll need it for Laravel configuration.</p><h3>Part 4: Setting Up Cloud Storage</h3><p>Cloud Storage handles all your file uploads with automatic global CDN.</p><h3>Create Storage Bucket</h3><pre>gsutil mb -p connect-backend-prod \<br>  -c STANDARD \<br>  -l me-central2 \<br>  gs://connect-storage-prod</pre><h3>Enable Versioning (Optional but Recommended)</h3><pre>gsutil versioning set on gs://connect-storage-prod</pre><p>This allows you to recover accidentally deleted files.</p><h3>Configure Lifecycle Policy</h3><p>Automatically delete old temporary files:</p><pre>// lifecycle.json<br>{<br>  &quot;lifecycle&quot;: {<br>    &quot;rule&quot;: [{<br>      &quot;action&quot;: {&quot;type&quot;: &quot;Delete&quot;},<br>      &quot;condition&quot;: {&quot;age&quot;: 90}<br>    }]<br>  }<br>}</pre><pre>gsutil lifecycle set lifecycle.json gs://connect-storage-prod</pre><h3>Setup CORS</h3><p>Allow uploads from your domain:</p><pre>// cors.json<br>[{<br>  &quot;origin&quot;: [&quot;https://yourdomain.com&quot;],<br>  &quot;method&quot;: [&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;],<br>  &quot;responseHeader&quot;: [&quot;Content-Type&quot;],<br>  &quot;maxAgeSeconds&quot;: 3600<br>}]</pre><pre>gsutil cors set cors.json gs://connect-storage-prod</pre><h3>Part 5: Dockerizing Your Laravel Application</h3><p>Now let’s containerize your Laravel app for Cloud Run.</p><h3>Create Optimized Dockerfile</h3><pre># Dockerfile<br>FROM php:8.2-fpm-alpine<br><br># Install system dependencies<br>RUN apk add --no-cache \<br>    nginx \<br>    supervisor \<br>    curl \<br>    libpng-dev \<br>    libzip-dev \<br>    zip \<br>    unzip<br># Install PHP extensions<br>RUN docker-php-ext-install \<br>    pdo_mysql \<br>    bcmath \<br>    gd \<br>    zip \<br>    opcache<br># Install Redis extension<br>RUN pecl install redis &amp;&amp; docker-php-ext-enable redis<br># Install Composer<br>COPY --from=composer:latest /usr/bin/composer /usr/bin/composer<br># Set working directory<br>WORKDIR /app<br># Copy composer files<br>COPY composer.json composer.lock ./<br># Install dependencies<br>RUN composer install \<br>    --no-dev \<br>    --no-scripts \<br>    --no-autoloader \<br>    --prefer-dist<br># Copy application code<br>COPY . .<br># Generate autoloader<br>RUN composer dump-autoload --optimize<br># Set permissions<br>RUN chown -R www-data:www-data storage bootstrap/cache<br># Copy configurations<br>COPY docker/nginx.conf /etc/nginx/http.d/default.conf<br>COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf<br>COPY docker/php.ini /usr/local/etc/php/conf.d/custom.ini<br># Optimize for production<br>RUN php artisan config:cache &amp;&amp; \<br>    php artisan route:cache &amp;&amp; \<br>    php artisan view:cache<br>EXPOSE 8080<br>CMD [&quot;/usr/bin/supervisord&quot;, &quot;-c&quot;, &quot;/etc/supervisor/conf.d/supervisord.conf&quot;]</pre><h3>Create Nginx Configuration</h3><pre># docker/nginx.conf<br>server {<br>    listen 8080;<br>    server_name _;<br>    root /app/public;<br>    index index.php;<br>    location / {<br>        try_files $uri $uri/ /index.php?$query_string;<br>    }<br>    location ~ \.php$ {<br>        fastcgi_pass unix:/var/run/php-fpm.sock;<br>        fastcgi_index index.php;<br>        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;<br>        include fastcgi_params;<br>        fastcgi_read_timeout 300;<br>    }<br>    client_max_body_size 100M;<br>}</pre><h3>Create Supervisor Configuration</h3><pre># docker/supervisord.conf<br>[supervisord]<br>nodaemon=true<br>user=root<br>logfile=/dev/stdout<br>logfile_maxbytes=0<br><br>[program:php-fpm]<br>command=/usr/local/sbin/php-fpm --nodaemonize<br>autostart=true<br>autorestart=true<br>stdout_logfile=/dev/stdout<br>stderr_logfile=/dev/stderr<br>[program:nginx]<br>command=/usr/sbin/nginx -g &quot;daemon off;&quot;<br>autostart=true<br>autorestart=true<br>stdout_logfile=/dev/stdout<br>stderr_logfile=/dev/stderr</pre><h3>Build and Test Locally</h3><pre># Build image<br>docker build -t connect-backend .<br><br># Run locally<br>docker run -p 8080:8080 \<br>  -e DB_HOST=localhost \<br>  -e DB_DATABASE=laravel \<br>  -e DB_USERNAME=root \<br>  -e DB_PASSWORD=secret \<br>  connect-backend<br># Test<br>curl http://localhost:8080/api/health</pre><h3>Part 6: Configuring Laravel for GCP</h3><h3>Install Required Packages</h3><pre>composer require superbalist/laravel-google-cloud-storage<br>composer require predis/predis<br>composer require laravel/horizon</pre><h3>Configure Filesystem (config/filesystems.php)</h3><pre>&#39;disks&#39; =&gt; [<br>    &#39;gcs&#39; =&gt; [<br>        &#39;driver&#39; =&gt; &#39;gcs&#39;,<br>        &#39;project_id&#39; =&gt; env(&#39;GCS_PROJECT_ID&#39;),<br>        &#39;key_file&#39; =&gt; env(&#39;GOOGLE_APPLICATION_CREDENTIALS&#39;),<br>        &#39;bucket&#39; =&gt; env(&#39;GCS_BUCKET&#39;),<br>        &#39;path_prefix&#39; =&gt; env(&#39;GCS_PATH_PREFIX&#39;, &#39;&#39;),<br>        &#39;visibility&#39; =&gt; &#39;public&#39;,<br>    ],<br>],<br>&#39;default&#39; =&gt; env(&#39;FILESYSTEM_DISK&#39;, &#39;gcs&#39;),</pre><h3>Configure Database (config/database.php)</h3><pre>&#39;connections&#39; =&gt; [<br>    &#39;mysql&#39; =&gt; [<br>        &#39;driver&#39; =&gt; &#39;mysql&#39;,<br>        &#39;unix_socket&#39; =&gt; env(&#39;DB_SOCKET&#39;), // For Cloud SQL<br>        &#39;host&#39; =&gt; env(&#39;DB_HOST&#39;, &#39;127.0.0.1&#39;),<br>        &#39;database&#39; =&gt; env(&#39;DB_DATABASE&#39;),<br>        &#39;username&#39; =&gt; env(&#39;DB_USERNAME&#39;),<br>        &#39;password&#39; =&gt; env(&#39;DB_PASSWORD&#39;),<br>        &#39;charset&#39; =&gt; &#39;utf8mb4&#39;,<br>        &#39;collation&#39; =&gt; &#39;utf8mb4_unicode_ci&#39;,<br>    ],<br>],</pre><h3>Create File Upload Service</h3><pre>// app/Services/FileUploadService.php<br>namespace App\Services;<br><br>use Illuminate\Http\UploadedFile;<br>use Illuminate\Support\Facades\Storage;<br>use Intervention\Image\Facades\Image;<br>class FileUploadService<br>{<br>    public function uploadImage(UploadedFile $file, string $path = &#39;images&#39;): array<br>    {<br>        $filename = time() . &#39;_&#39; . $file-&gt;hashName();<br>        <br>        $sizes = [<br>            &#39;thumbnail&#39; =&gt; [&#39;width&#39; =&gt; 150, &#39;height&#39; =&gt; 150],<br>            &#39;medium&#39; =&gt; [&#39;width&#39; =&gt; 500, &#39;height&#39; =&gt; 500],<br>            &#39;large&#39; =&gt; [&#39;width&#39; =&gt; 1200, &#39;height&#39; =&gt; 1200],<br>        ];<br>        <br>        $paths = [];<br>        <br>        // Upload original<br>        $originalPath = &quot;{$path}/original/{$filename}&quot;;<br>        Storage::disk(&#39;gcs&#39;)-&gt;put($originalPath, file_get_contents($file));<br>        $paths[&#39;original&#39;] = Storage::disk(&#39;gcs&#39;)-&gt;url(https://medium.com/$originalPath);<br>        <br>        // Create thumbnails<br>        foreach ($sizes as $size =&gt; $config) {<br>            $image = Image::make($file)<br>                -&gt;fit($config[&#39;width&#39;], $config[&#39;height&#39;])<br>                -&gt;encode(&#39;jpg&#39;, 85);<br>            <br>            $sizePath = &quot;{$path}/{$size}/{$filename}&quot;;<br>            Storage::disk(&#39;gcs&#39;)-&gt;put($sizePath, $image);<br>            $paths[$size] = Storage::disk(&#39;gcs&#39;)-&gt;url(https://medium.com/$sizePath);<br>        }<br>        <br>        return [<br>            &#39;filename&#39; =&gt; $filename,<br>            &#39;paths&#39; =&gt; $paths,<br>        ];<br>    }<br>}</pre><h3>Create Health Check Endpoints</h3><pre>// routes/api.php<br>Route::get(&#39;/health&#39;, function () {<br>    return response()-&gt;json([<br>        &#39;status&#39; =&gt; &#39;healthy&#39;,<br>        &#39;timestamp&#39; =&gt; now(),<br>    ]);<br>});<br><br>Route::get(&#39;/health/deep&#39;, function () {<br>    $checks = [];<br>    <br>    // Database<br>    try {<br>        DB::connection()-&gt;getPdo();<br>        $checks[&#39;database&#39;] = &#39;ok&#39;;<br>    } catch (\Exception $e) {<br>        $checks[&#39;database&#39;] = &#39;failed&#39;;<br>    }<br>    <br>    // Redis<br>    try {<br>        Redis::set(&#39;health&#39;, &#39;ok&#39;);<br>        $checks[&#39;redis&#39;] = Redis::get(&#39;health&#39;) === &#39;ok&#39; ? &#39;ok&#39; : &#39;failed&#39;;<br>    } catch (\Exception $e) {<br>        $checks[&#39;redis&#39;] = &#39;failed&#39;;<br>    }<br>    <br>    // Storage<br>    try {<br>        Storage::disk(&#39;gcs&#39;)-&gt;put(&#39;health.txt&#39;, &#39;ok&#39;);<br>        $checks[&#39;storage&#39;] = &#39;ok&#39;;<br>        Storage::disk(&#39;gcs&#39;)-&gt;delete(&#39;health.txt&#39;);<br>    } catch (\Exception $e) {<br>        $checks[&#39;storage&#39;] = &#39;failed&#39;;<br>    }<br>    <br>    $healthy = collect($checks)-&gt;every(fn($v) =&gt; $v === &#39;ok&#39;);<br>    <br>    return response()-&gt;json([<br>        &#39;status&#39; =&gt; $healthy ? &#39;healthy&#39; : &#39;unhealthy&#39;,<br>        &#39;checks&#39; =&gt; $checks,<br>    ], $healthy ? 200 : 503);<br>});</pre><h3>Part 7: Deploying to Cloud Run</h3><h3>Create Environment Configuration</h3><pre># env.production.yaml<br>APP_NAME: &quot;My Laravel App&quot;<br>APP_ENV: production<br>APP_DEBUG: &quot;false&quot;<br>APP_URL: https://yourdomain.com<br>DB_CONNECTION: mysql<br>DB_SOCKET: /cloudsql/PROJECT_ID:REGION:INSTANCE_NAME<br>DB_DATABASE: laravel_db<br>DB_USERNAME: laravel-user<br>REDIS_HOST: 10.0.0.5<br>REDIS_PORT: &quot;6379&quot;<br>CACHE_DRIVER: redis<br>SESSION_DRIVER: redis<br>QUEUE_CONNECTION: redis<br>FILESYSTEM_DISK: gcs<br>GCS_PROJECT_ID: connect-backend-prod<br>GCS_BUCKET: connect-storage-prod<br>LOG_CHANNEL: stderr<br>LOG_LEVEL: error</pre><h3>Deploy Backend Service</h3><pre># Build and push to Container Registry<br>gcloud builds submit --tag gcr.io/connect-backend-prod/laravel-app<br><br># Deploy to Cloud Run<br>gcloud run deploy laravel-backend \<br>  --image=gcr.io/connect-backend-prod/laravel-app \<br>  --region=me-central2 \<br>  --platform=managed \<br>  --set-env-vars-file=env.production.yaml \<br>  --set-secrets=DB_PASSWORD=db-password:latest,APP_KEY=app-key:latest \<br>  --add-cloudsql-instances=connect-backend-prod:me-central2:connect-db-prod \<br>  --vpc-connector=connect-vpc-connector \<br>  --allow-unauthenticated \<br>  --min-instances=1 \<br>  --max-instances=50 \<br>  --memory=4Gi \<br>  --cpu=4 \<br>  --timeout=300 \<br>  --concurrency=80</pre><p><strong>Important flags:</strong></p><ul><li>--min-instances=1 — Always have 1 instance ready (no cold starts)</li><li>--max-instances=50 — Scale up to 50 instances during traffic spikes</li><li>--memory=4Gi — 4GB per instance (adjust based on needs)</li><li>--concurrency=80 — Handle 80 concurrent requests per instance</li><li>--timeout=300 — 5-minute timeout for long-running requests</li></ul><h3>Deploy Worker Service (for Queues)</h3><pre>gcloud run deploy laravel-worker \<br>  --image=gcr.io/connect-backend-prod/laravel-app \<br>  --region=me-central2 \<br>  --platform=managed \<br>  --set-env-vars-file=env.production.yaml \<br>  --set-secrets=DB_PASSWORD=db-password:latest \<br>  --add-cloudsql-instances=connect-backend-prod:me-central2:connect-db-prod \<br>  --vpc-connector=connect-vpc-connector \<br>  --no-allow-unauthenticated \<br>  --min-instances=1 \<br>  --max-instances=5 \<br>  --memory=1Gi \<br>  --cpu=1 \<br>  --command=php \<br>  --args=artisan,horizon</pre><h3>Part 8: Setting Up CI/CD with Bitbucket Pipelines</h3><h3>Create bitbucket-pipelines.yml</h3><pre>image: google/cloud-sdk:alpine<br><br>pipelines:<br>  branches:<br>    main:<br>      - step:<br>          name: Deploy to Production<br>          deployment: production<br>          trigger: manual<br>          script:<br>            # Authenticate<br>            - echo $GCP_SERVICE_KEY | base64 -d &gt; gcp-key.json<br>            - gcloud auth activate-service-account --key-file gcp-key.json<br>            - gcloud config set project connect-backend-prod<br>            <br>            # Build<br>            - gcloud builds submit --tag gcr.io/connect-backend-prod/laravel-app<br>            <br>            # Deploy<br>            - gcloud run deploy laravel-backend<br>                --image=gcr.io/connect-backend-prod/laravel-app<br>                --region=me-central2<br>                ... (add all flags from above)<br>            <br>            # Run migrations<br>            - gcloud run jobs create migrate<br>                --image=gcr.io/connect-backend-prod/laravel-app<br>                --command=php<br>                --args=artisan,migrate,--force<br>            - gcloud run jobs execute migrate --wait</pre><h3>Setup Service Account</h3><pre># Create service account for CI/CD<br>gcloud iam service-accounts create bitbucket-deployer \<br>  --display-name=&quot;Bitbucket CI/CD&quot;<br><br># Grant necessary roles<br>gcloud projects add-iam-policy-binding connect-backend-prod \<br>  --member=&quot;serviceAccount:bitbucket-deployer@connect-backend-prod.iam.gserviceaccount.com&quot; \<br>  --role=&quot;roles/run.admin&quot;<br>gcloud projects add-iam-policy-binding connect-backend-prod \<br>  --member=&quot;serviceAccount:bitbucket-deployer@connect-backend-prod.iam.gserviceaccount.com&quot; \<br>  --role=&quot;roles/cloudbuild.builds.editor&quot;<br># Generate key<br>gcloud iam service-accounts keys create bitbucket-key.json \<br>  --iam-account=bitbucket-deployer@connect-backend-prod.iam.gserviceaccount.com<br># Encode for Bitbucket<br>cat bitbucket-key.json | base64</pre><p>Add the base64 output as GCP_SERVICE_KEY in Bitbucket environment variables.</p><h3>Part 9: Advanced Features</h3><h3>1. Setup Laravel Horizon for Queue Monitoring</h3><pre>composer require laravel/horizon<br>php artisan horizon:install</pre><p><strong>Protect dashboard:</strong></p><pre>// app/Providers/HorizonServiceProvider.php<br>protected function gate()<br>{<br>    Gate::define(&#39;viewHorizon&#39;, function ($user) {<br>        return in_array($user-&gt;email, [&#39;admin@yourdomain.com&#39;]);<br>    });<br>}</pre><h3>2. Setup Cron Jobs with Cloud Scheduler</h3><pre># Create scheduler service account<br>gcloud iam service-accounts create cloud-scheduler<br><br># Grant invoker permission<br>gcloud run services add-iam-policy-binding laravel-backend \<br>  --member=&quot;serviceAccount:cloud-scheduler@connect-backend-prod.iam.gserviceaccount.com&quot; \<br>  --role=&quot;roles/run.invoker&quot;<br><br># Create schedule job (every minute)<br>gcloud scheduler jobs create http laravel-cron \<br>  --location=me-central2 \<br>  --schedule=&quot;* * * * *&quot; \<br>  --uri=&quot;https://yourdomain.com/api/cron/run&quot; \<br>  --http-method=POST \<br>  --oidc-service-account-email=cloud-scheduler@connect-backend-prod.iam.gserviceaccount.com</pre><p><strong>Create endpoint:</strong></p><pre>// routes/api.php<br>Route::post(&#39;/cron/run&#39;, function () {<br>    if (!request()-&gt;hasHeader(&#39;X-Cloudscheduler&#39;)) {<br>        abort(403);<br>    }<br>    <br>    Artisan::call(&#39;schedule:run&#39;);<br>    <br>    return response()-&gt;json([&#39;success&#39; =&gt; true]);<br>});</pre><h3>3. Setup Monitoring &amp; Alerts</h3><pre># Create alert for high error rate<br>gcloud alpha monitoring policies create \<br>  --notification-channels=CHANNEL_ID \<br>  --display-name=&quot;High Error Rate&quot; \<br>  --condition-threshold-value=100 \<br>  --condition-threshold-duration=300s</pre><h3>Part 10: Cost Optimization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Grm0WnCzfCPRNLRFnEfZfA.jpeg" /></figure><h3>Current Monthly Costs (Production)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*2OWsUUOJmtaBZyaAmeqjEQ.png" /></figure><h3>Optimization Tips</h3><p><strong>1. Use Committed Use Discounts</strong></p><ul><li>1-year commitment: Save 25%</li><li>3-year commitment: Save 52%</li></ul><p><strong>2. Scale to Zero on Staging</strong></p><pre>--min-instances=0  # On staging environment</pre><p><strong>3. Implement Aggressive Caching</strong></p><pre>// Cache expensive queries<br>$properties = Cache::remember(&#39;properties&#39;, 3600, function () {<br>    return Property::with(&#39;images&#39;)-&gt;get();<br>});</pre><p><strong>4. Use CDN for Static Assets</strong></p><pre>gsutil web set -m index.html -e 404.html gs://connect-storage-prod<br>gsutil iam ch allUsers:objectViewer gs://connect-storage-prod</pre><p><strong>5. Monitor and Set Budgets</strong></p><pre>gcloud billing budgets create \<br>  --billing-account=BILLING_ACCOUNT_ID \<br>  --display-name=&quot;Monthly Budget&quot; \<br>  --budget-amount=1000USD \<br>  --threshold-rule=percent=80</pre><h3>Troubleshooting Common Issues</h3><h3>Issue 1: Cloud SQL Connection Failed</h3><p><strong>Error:</strong> SQLSTATE[HY000] [2002] Connection refused</p><p><strong>Solution:</strong></p><pre># Verify Cloud SQL connector is enabled<br>gcloud run services describe laravel-backend \<br>  --format=&quot;value(spec.template.metadata.annotations[run.googleapis.com/cloudsql-instances])&quot;<br># Grant Cloud SQL Client role<br>gcloud projects add-iam-policy-binding PROJECT_ID \<br>  --member=&quot;serviceAccount:SERVICE_ACCOUNT&quot; \<br>  --role=&quot;roles/cloudsql.client&quot;</pre><h3>Issue 2: File Upload Failed</h3><p><strong>Error:</strong> Unable to write file to disk</p><p><strong>Solution:</strong></p><pre># Check service account has storage permissions<br>gsutil iam get gs://connect-storage-prod<br># Grant object admin role<br>gsutil iam ch serviceAccount:SERVICE_ACCOUNT:roles/storage.objectAdmin \<br>  gs://connect-storage-prod</pre><h3>Issue 3: Redis Timeout</h3><p><strong>Error:</strong> Connection timed out [tcp://10.0.0.5:6379]</p><p><strong>Solution:</strong></p><pre># Verify VPC connector<br>gcloud compute networks vpc-access connectors describe connect-vpc-connector \<br>  --region=me-central2</pre><pre># Check Redis is accessible<br>gcloud redis instances describe connect-redis --region=me-central2</pre><h3>Security Best Practices</h3><h3>1. Always Use Secrets Manager</h3><p>❌ <strong>Never do this:</strong></p><pre>DB_PASSWORD: &quot;my_password_123&quot;</pre><p>✅ <strong>Do this:</strong></p><pre>--set-secrets=DB_PASSWORD=db-password:latest</pre><h3>2. Disable Public IP on Cloud SQL</h3><pre>--no-assign-ip  # No public access</pre><h3>3. Use VPC for Private Communication</h3><p>All services should communicate through private IPs only.</p><h3>4. Enable Deletion Protection</h3><pre>--deletion-protection  # On production databases</pre><h3>5. Rotate Secrets Regularly</h3><pre># Create new version<br>echo -n &#39;NEW_PASSWORD&#39; | gcloud secrets versions add db-password --data-file=-<br># Update Cloud Run to use new version<br>gcloud run services update laravel-backend \<br>  --update-secrets=DB_PASSWORD=db-password:latest</pre><h3>Performance Optimization</h3><h3>1. Laravel Octane</h3><p>For even better performance, use Laravel Octane:</p><pre>composer require laravel/octane<br>php artisan octane:install --server=swoole</pre><p>Update Dockerfile:</p><pre>CMD [&quot;php&quot;, &quot;artisan&quot;, &quot;octane:start&quot;, &quot;--server=swoole&quot;, &quot;--host=0.0.0.0&quot;, &quot;--port=8080&quot;]</pre><h3>2. Database Query Optimization</h3><pre>// Use eager loading<br>$properties = Property::with([&#39;owner&#39;, &#39;images&#39;])-&gt;get();<br>// Use chunking for large datasets<br>Property::chunk(1000, function ($properties) {<br>    foreach ($properties as $property) {<br>        // Process<br>    }<br>});<br>// Add indexes<br>Schema::table(&#39;properties&#39;, function (Blueprint $table) {<br>    $table-&gt;index(&#39;status&#39;);<br>    $table-&gt;index([&#39;city&#39;, &#39;status&#39;]);<br>});</pre><h3>3. Response Caching</h3><pre>use Illuminate\Support\Facades\Cache;<br><br>Route::get(&#39;/api/properties&#39;, function () {<br>    return Cache::remember(&#39;properties.all&#39;, 3600, function () {<br>        return Property::all();<br>    });<br>});</pre><h3>Monitoring &amp; Maintenance</h3><h3>View Logs</h3><p>bash</p><pre># Real-time logs<br>gcloud run services logs tail laravel-backend --region=me-central2<br># Filter errors<br>gcloud run services logs read laravel-backend \<br>  --log-filter=&#39;severity&gt;=ERROR&#39; \<br>  --limit=100</pre><h3>Check Performance Metrics</h3><p>bash</p><pre># CPU usage<br>gcloud monitoring time-series list \<br>  --filter=&#39;metric.type=&quot;run.googleapis.com/container/cpu/utilizations&quot;&#39;<br># Memory usage<br>gcloud monitoring time-series list \<br>  --filter=&#39;metric.type=&quot;run.googleapis.com/container/memory/utilizations&quot;&#39;</pre><h3>Backup Strategies</h3><p><strong>Automated Database Backups:</strong></p><p>Cloud SQL automatically backs up daily. To restore:</p><p>bash</p><pre># List backups<br>gcloud sql backups list --instance=connect-db-prod<br># Restore from backup<br>gcloud sql backups restore BACKUP_ID --backup-instance=connect-db-prod</pre><p><strong>Storage Backups:</strong></p><pre># Sync to backup bucket<br>gsutil -m rsync -r gs://connect-storage-prod/ gs://connect-backups-prod/</pre><h3>Conclusion</h3><p>Congratulations! 🎉 You now have a production-ready Laravel application running on Google Cloud Platform with:</p><p>✅ <strong>Auto-scaling infrastructure</strong> that handles traffic spikes <br>✅ <strong>Fully managed database</strong> with automatic backups <br>✅ <strong>High-performance caching</strong> with Redis <br>✅ <strong>Scalable file storage</strong> with global CDN <br>✅ <strong>Secure secrets management</strong> <br>✅ <strong>Automated deployments</strong> with CI/CD <br>✅ <strong>Cost-optimized</strong> infrastructure (~$750/month for 100K users)</p><h3>What’s Next?</h3><ol><li><strong>Add Custom Domain</strong> — Map your domain to Cloud Run</li><li><strong>Setup CDN</strong> — Enable Cloud CDN for faster asset delivery</li><li><strong>Implement Monitoring</strong> — Setup comprehensive monitoring and alerts</li><li><strong>Add DDoS Protection</strong> — Enable Cloud Armor for security</li><li><strong>Optimize Costs</strong> — Implement committed use discounts</li></ol><h3>Useful Resources</h3><ul><li><a href="https://cloud.google.com/architecture">GCP Architecture Best Practices</a></li><li><a href="https://laravel.com/docs/deployment">Laravel Deployment Checklist</a></li><li><a href="https://cloud.google.com/run/docs">Cloud Run Documentation</a></li></ul><h3>About the Author</h3><p><strong>Ahmed</strong> is a Senior Laravel Developer at Munjz, specializing in cloud infrastructure and scalable web applications. With 8+ years of experience deploying Laravel apps on various platforms, he’s passionate about helping developers build robust, production-ready applications.</p><p><strong>Connect:</strong></p><ul><li>LinkedIn: <a href="https://www.linkedin.com/in/ahmedebead">Ahmed Mohamed</a></li></ul><p><em>Did you find this guide helpful? Give it a clap 👏 and share it with your team! Have questions? Drop them in the comments below.</em></p><p><em>Want more Laravel + GCP content? Follow me for updates on advanced topics like Laravel Octane on Cloud Run, Multi-region deployments, and Cost optimization strategies.</em></p><p><strong>Tags:</strong> #Laravel #GoogleCloud #CloudRun #DevOps #PHP #Backend #CloudSQL #Deployment #Tutorial #WebDevelopment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22f1dfade6ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Laravel Macros: Advanced Real-World Examples]]></title>
            <link>https://medium.com/@ahmedm3bead/mastering-laravel-macros-advanced-real-world-examples-1986ddfa6aa9?source=rss-7bad226600ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/1986ddfa6aa9</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[macro]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Ahmed Ebead]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 10:56:26 GMT</pubDate>
            <atom:updated>2025-10-23T10:56:26.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgh0D-sbfI8MT39pchNleA.png" /></figure><h3>Mastering Laravel Macros: Advanced Real-World Examples</h3><p>Laravel’s macro system is one of those hidden gems that can transform how you write clean, maintainable code. If you’ve ever found yourself repeating the same collection manipulations, query builder patterns, or request validations across your application, macros are about to become your new best friend.</p><h3>What Are Laravel Macros?</h3><p>Macros allow you to extend Laravel’s core classes at runtime without inheritance or modifying the framework itself. They’re powered by PHP’s magic __call method and Laravel&#39;s Macroable trait, enabling you to add custom methods to classes like Collection, Request, Response, QueryBuilder, and more.</p><p>Think of macros as a way to teach Laravel new tricks that perfectly fit your application’s needs.</p><h3>The Anatomy of a Macro</h3><p>Before diving into advanced examples, let’s understand the basic structure:</p><pre>use Illuminate\Support\Collection;<br><br>Collection::macro(&#39;toUpper&#39;, function () {<br>    return $this-&gt;map(fn($item) =&gt; strtoupper($item));<br>});<br>// Usage<br>collect([&#39;hello&#39;, &#39;world&#39;])-&gt;toUpper(); // [&#39;HELLO&#39;, &#39;WORLD&#39;]</pre><p>The $this context refers to the instance of the class you&#39;re extending, giving you full access to all its properties and methods.</p><h3>Real-World Example 1: Advanced Collection Statistics</h3><p>Let’s build a macro that calculates comprehensive statistics for numerical collections — something you might need in analytics dashboards or reporting systems.</p><pre>use Illuminate\Support\Collection;<br><br>Collection::macro(&#39;statistics&#39;, function () {<br>    $values = $this-&gt;values()-&gt;sort();<br>    $count = $values-&gt;count();<br>    <br>    if ($count === 0) {<br>        return null;<br>    }<br>    <br>    $mean = $values-&gt;average();<br>    $median = $count % 2 === 0<br>        ? ($values[$count / 2 - 1] + $values[$count / 2]) / 2<br>        : $values[floor($count / 2)];<br>    <br>    $variance = $values-&gt;map(fn($x) =&gt; pow($x - $mean, 2))-&gt;average();<br>    $stdDev = sqrt($variance);<br>    <br>    $q1Index = floor($count * 0.25);<br>    $q3Index = floor($count * 0.75);<br>    <br>    return [<br>        &#39;count&#39; =&gt; $count,<br>        &#39;min&#39; =&gt; $values-&gt;min(),<br>        &#39;max&#39; =&gt; $values-&gt;max(),<br>        &#39;mean&#39; =&gt; round($mean, 2),<br>        &#39;median&#39; =&gt; round($median, 2),<br>        &#39;std_dev&#39; =&gt; round($stdDev, 2),<br>        &#39;variance&#39; =&gt; round($variance, 2),<br>        &#39;q1&#39; =&gt; $values[$q1Index],<br>        &#39;q3&#39; =&gt; $values[$q3Index],<br>        &#39;iqr&#39; =&gt; $values[$q3Index] - $values[$q1Index],<br>    ];<br>});<br>// Usage in a dashboard controller<br>$salesData = Order::whereMonth(&#39;created_at&#39;, now()-&gt;month)<br>    -&gt;pluck(&#39;total&#39;)<br>    -&gt;statistics();<br>/*<br>Result:<br>[<br>    &#39;count&#39; =&gt; 150,<br>    &#39;min&#39; =&gt; 12.50,<br>    &#39;max&#39; =&gt; 2450.00,<br>    &#39;mean&#39; =&gt; 342.75,<br>    &#39;median&#39; =&gt; 289.00,<br>    &#39;std_dev&#39; =&gt; 156.23,<br>    ...<br>]<br>*/</pre><p>This macro transforms raw data into actionable insights with a single method call, perfect for business intelligence features.</p><h3>Real-World Example 2: Query Builder Time-Based Filters</h3><p>Building time-range filters is incredibly common. Let’s create macros that make temporal queries elegant and reusable.</p><pre>use Illuminate\Database\Query\Builder;<br>use Carbon\Carbon;<br><br>Builder::macro(&#39;whereDateBetween&#39;, function ($column, $start, $end = null) {<br>    $end = $end ?? now();<br>    <br>    return $this-&gt;whereDate($column, &#39;&gt;=&#39;, Carbon::parse($start))<br>                -&gt;whereDate($column, &#39;&lt;=&#39;, Carbon::parse($end));<br>});<br>Builder::macro(&#39;whereRecent&#39;, function ($column, $days = 7) {<br>    return $this-&gt;whereDate($column, &#39;&gt;=&#39;, now()-&gt;subDays($days));<br>});<br>Builder::macro(&#39;whereBusinessHours&#39;, function ($column) {<br>    return $this-&gt;whereTime($column, &#39;&gt;=&#39;, &#39;09:00:00&#39;)<br>                -&gt;whereTime($column, &#39;&lt;=&#39;, &#39;17:00:00&#39;)<br>                -&gt;whereNotIn(\DB::raw(&#39;DAYOFWEEK(&#39; . $column . &#39;)&#39;), [1, 7]); // Exclude weekends<br>});<br>Builder::macro(&#39;whereQuarter&#39;, function ($column, $quarter, $year = null) {<br>    $year = $year ?? now()-&gt;year;<br>    $startMonth = ($quarter - 1) * 3 + 1;<br>    $endMonth = $startMonth + 2;<br>    <br>    return $this-&gt;whereYear($column, $year)<br>                -&gt;whereMonth($column, &#39;&gt;=&#39;, $startMonth)<br>                -&gt;whereMonth($column, &#39;&lt;=&#39;, $endMonth);<br>});<br>// Usage<br>$recentOrders = Order::whereRecent(&#39;created_at&#39;, 14)-&gt;get();<br>$businessHourTickets = Ticket::whereBusinessHours(&#39;created_at&#39;)<br>    -&gt;where(&#39;priority&#39;, &#39;high&#39;)<br>    -&gt;get();<br>$q4Sales = Sale::whereQuarter(&#39;sale_date&#39;, 4, 2024)-&gt;sum(&#39;amount&#39;);<br>$periodRevenue = Payment::whereDateBetween(&#39;paid_at&#39;, &#39;2024-01-01&#39;, &#39;2024-12-31&#39;)<br>    -&gt;sum(&#39;amount&#39;);</pre><p>These macros eliminate repetitive date logic and make your queries self-documenting.</p><h3>Real-World Example 3: Request Validation Macros</h3><p>Validation is at the heart of every application. Let’s create macros that handle common validation patterns.</p><pre>use Illuminate\Http\Request;<br><br>Request::macro(&#39;validatePhone&#39;, function ($field = &#39;phone&#39;) {<br>    return $this-&gt;validate([<br>        $field =&gt; [&#39;required&#39;, &#39;regex:/^([0-9\s\-\+\(\)]*)$/&#39;, &#39;min:10&#39;, &#39;max:20&#39;]<br>    ]);<br>});<br>Request::macro(&#39;validateDateRange&#39;, function ($startField = &#39;start_date&#39;, $endField = &#39;end_date&#39;) {<br>    return $this-&gt;validate([<br>        $startField =&gt; [&#39;required&#39;, &#39;date&#39;],<br>        $endField =&gt; [&#39;required&#39;, &#39;date&#39;, &#39;after_or_equal:&#39; . $startField],<br>    ]);<br>});<br>Request::macro(&#39;validateCurrency&#39;, function ($field, $min = 0, $max = null) {<br>    $rules = [<br>        $field =&gt; [<br>            &#39;required&#39;,<br>            &#39;numeric&#39;,<br>            &#39;min:&#39; . $min,<br>            &#39;regex:/^\d+(\.\d{1,2})?$/&#39;<br>        ]<br>    ];<br>    <br>    if ($max !== null) {<br>        $rules[$field][] = &#39;max:&#39; . $max;<br>    }<br>    <br>    return $this-&gt;validate($rules);<br>});<br>Request::macro(&#39;hasAny&#39;, function (array $keys) {<br>    return collect($keys)-&gt;contains(fn($key) =&gt; $this-&gt;has($key));<br>});<br>Request::macro(&#39;onlyFilled&#39;, function (array $keys) {<br>    return collect($this-&gt;only($keys))<br>        -&gt;filter(fn($value) =&gt; filled($value))<br>        -&gt;toArray();<br>});<br>// Usage in controllers<br>public function store(Request $request)<br>{<br>    $request-&gt;validatePhone();<br>    $request-&gt;validateDateRange(&#39;start_date&#39;, &#39;end_date&#39;);<br>    $request-&gt;validateCurrency(&#39;price&#39;, 0.01, 999999.99);<br>    <br>    // Only get filled values, ignoring empty strings and nulls<br>    $data = $request-&gt;onlyFilled([&#39;name&#39;, &#39;description&#39;, &#39;notes&#39;]);<br>    <br>    // Check if any optional field is present<br>    if ($request-&gt;hasAny([&#39;coupon_code&#39;, &#39;promo_code&#39;, &#39;discount_code&#39;])) {<br>        // Apply discount logic<br>    }<br>}</pre><h3>Real-World Example 4: Response Formatting Macros</h3><p>Consistent API responses are crucial for frontend teams. Let’s build standardized response macros.</p><pre>use Illuminate\Http\Response;<br>use Illuminate\Support\Facades\Response as ResponseFacade;<br><br>ResponseFacade::macro(&#39;success&#39;, function ($data = null, $message = &#39;Success&#39;, $code = 200) {<br>    return response()-&gt;json([<br>        &#39;success&#39; =&gt; true,<br>        &#39;message&#39; =&gt; $message,<br>        &#39;data&#39; =&gt; $data,<br>        &#39;timestamp&#39; =&gt; now()-&gt;toISOString(),<br>    ], $code);<br>});<br>ResponseFacade::macro(&#39;error&#39;, function ($message = &#39;Error&#39;, $errors = [], $code = 400) {<br>    return response()-&gt;json([<br>        &#39;success&#39; =&gt; false,<br>        &#39;message&#39; =&gt; $message,<br>        &#39;errors&#39; =&gt; $errors,<br>        &#39;timestamp&#39; =&gt; now()-&gt;toISOString(),<br>    ], $code);<br>});<br>ResponseFacade::macro(&#39;paginated&#39;, function ($paginator, $message = &#39;Success&#39;) {<br>    return response()-&gt;json([<br>        &#39;success&#39; =&gt; true,<br>        &#39;message&#39; =&gt; $message,<br>        &#39;data&#39; =&gt; $paginator-&gt;items(),<br>        &#39;meta&#39; =&gt; [<br>            &#39;current_page&#39; =&gt; $paginator-&gt;currentPage(),<br>            &#39;per_page&#39; =&gt; $paginator-&gt;perPage(),<br>            &#39;total&#39; =&gt; $paginator-&gt;total(),<br>            &#39;last_page&#39; =&gt; $paginator-&gt;lastPage(),<br>        ],<br>        &#39;links&#39; =&gt; [<br>            &#39;first&#39; =&gt; $paginator-&gt;url(https://medium.com/1),<br>            &#39;last&#39; =&gt; $paginator-&gt;url(https://medium.com/$paginator-&gt;lastPage()),<br>            &#39;prev&#39; =&gt; $paginator-&gt;previousPageUrl(),<br>            &#39;next&#39; =&gt; $paginator-&gt;nextPageUrl(),<br>        ],<br>        &#39;timestamp&#39; =&gt; now()-&gt;toISOString(),<br>    ]);<br>});<br>// Usage<br>return response()-&gt;success($user, &#39;User created successfully&#39;, 201);<br>return response()-&gt;error(&#39;Validation failed&#39;, $validator-&gt;errors(), 422);<br>return response()-&gt;paginated(<br>    User::paginate(15),<br>    &#39;Users retrieved successfully&#39;<br>);</pre><h3>Real-World Example 5: String Helper Macros</h3><p>Let’s extend Laravel’s Str class with practical string manipulation methods.</p><pre>use Illuminate\Support\Str;<br><br>Str::macro(&#39;maskEmail&#39;, function ($email) {<br>    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {<br>        return $email;<br>    }<br>    <br>    [$name, $domain] = explode(&#39;@&#39;, $email);<br>    $nameLength = strlen($name);<br>    <br>    if ($nameLength &lt;= 2) {<br>        $masked = str_repeat(&#39;*&#39;, $nameLength);<br>    } else {<br>        $masked = substr($name, 0, 2) . str_repeat(&#39;*&#39;, $nameLength - 2);<br>    }<br>    <br>    return $masked . &#39;@&#39; . $domain;<br>});<br>Str::macro(&#39;truncateWords&#39;, function ($string, $words = 20, $end = &#39;...&#39;) {<br>    $wordsArray = explode(&#39; &#39;, $string);<br>    <br>    if (count($wordsArray) &lt;= $words) {<br>        return $string;<br>    }<br>    <br>    return implode(&#39; &#39;, array_slice($wordsArray, 0, $words)) . $end;<br>});<br>Str::macro(&#39;toSlug&#39;, function ($string, $separator = &#39;-&#39;) {<br>    $string = mb_strtolower($string);<br>    $string = preg_replace(&#39;/[^\w\s-]/&#39;, &#39;&#39;, $string);<br>    $string = preg_replace(&#39;/[\s_]+/&#39;, $separator, $string);<br>    $string = trim($string, $separator);<br>    <br>    return $string;<br>});<br>Str::macro(&#39;extractHashtags&#39;, function ($text) {<br>    preg_match_all(&#39;/#(\w+)/&#39;, $text, $matches);<br>    return collect($matches[1])-&gt;unique()-&gt;values();<br>});<br>Str::macro(&#39;extractMentions&#39;, function ($text) {<br>    preg_match_all(&#39;/@(\w+)/&#39;, $text, $matches);<br>    return collect($matches[1])-&gt;unique()-&gt;values();<br>});<br>// Usage<br>Str::maskEmail(&#39;john.doe@example.com&#39;); // &quot;jo********@example.com&quot;<br>Str::truncateWords($article-&gt;content, 30); // First 30 words...<br>Str::toSlug(&#39;Hello World! This is a Test.&#39;); // &quot;hello-world-this-is-a-test&quot;<br>$hashtags = Str::extractHashtags(&#39;Check out #Laravel and #PHP!&#39;); // [&#39;Laravel&#39;, &#39;PHP&#39;]<br>$mentions = Str::extractMentions(&#39;Thanks @john and @jane!&#39;); // [&#39;john&#39;, &#39;jane&#39;]</pre><h3>Real-World Example 6: Model Scope Macros</h3><p>Enhance your Eloquent models with reusable query scopes through macros.</p><pre>use Illuminate\Database\Eloquent\Builder as EloquentBuilder;<br><br>EloquentBuilder::macro(&#39;whereLike&#39;, function ($column, $value) {<br>    return $this-&gt;where($column, &#39;LIKE&#39;, &quot;%{$value}%&quot;);<br>});<br>EloquentBuilder::macro(&#39;orWhereLike&#39;, function ($column, $value) {<br>    return $this-&gt;orWhere($column, &#39;LIKE&#39;, &quot;%{$value}%&quot;);<br>});<br>EloquentBuilder::macro(&#39;searchIn&#39;, function (array $columns, $term) {<br>    return $this-&gt;where(function ($query) use ($columns, $term) {<br>        foreach ($columns as $index =&gt; $column) {<br>            $method = $index === 0 ? &#39;where&#39; : &#39;orWhere&#39;;<br>            $query-&gt;$method($column, &#39;LIKE&#39;, &quot;%{$term}%&quot;);<br>        }<br>    });<br>});<br>EloquentBuilder::macro(&#39;withTrashed&#39;, function () {<br>    return $this-&gt;withTrashed();<br>});<br>EloquentBuilder::macro(&#39;active&#39;, function ($column = &#39;status&#39;, $value = &#39;active&#39;) {<br>    return $this-&gt;where($column, $value);<br>});<br>EloquentBuilder::macro(&#39;inactive&#39;, function ($column = &#39;status&#39;, $value = &#39;inactive&#39;) {<br>    return $this-&gt;where($column, $value);<br>});<br>// Usage<br>$users = User::searchIn([&#39;name&#39;, &#39;email&#39;, &#39;phone&#39;], &#39;john&#39;)-&gt;get();<br>$products = Product::whereLike(&#39;description&#39;, &#39;premium&#39;)<br>    -&gt;active()<br>    -&gt;get();<br>$posts = Post::searchIn([&#39;title&#39;, &#39;content&#39;, &#39;tags&#39;], $searchTerm)<br>    -&gt;whereRecent(&#39;published_at&#39;, 30)<br>    -&gt;paginate(20);</pre><h3>Organizing Your Macros</h3><p>For maintainability, organize macros in service providers. Create a dedicated MacroServiceProvider:</p><pre>namespace App\Providers;<br><br>use Illuminate\Support\ServiceProvider;<br>use Illuminate\Support\Collection;<br>use Illuminate\Database\Query\Builder;<br>use Illuminate\Http\Request;<br><br>class MacroServiceProvider extends ServiceProvider<br>{<br>    public function boot()<br>    {<br>        $this-&gt;registerCollectionMacros();<br>        $this-&gt;registerQueryMacros();<br>        $this-&gt;registerRequestMacros();<br>        $this-&gt;registerResponseMacros();<br>        $this-&gt;registerStringMacros();<br>    }<br>    <br>    protected function registerCollectionMacros()<br>    {<br>        Collection::macro(&#39;statistics&#39;, function () {<br>            // Implementation<br>        });<br>        <br>        // More collection macros...<br>    }<br>    <br>    protected function registerQueryMacros()<br>    {<br>        Builder::macro(&#39;whereDateBetween&#39;, function ($column, $start, $end = null) {<br>            // Implementation<br>        });<br>        <br>        // More query macros...<br>    }<br>    <br>    // Other macro registration methods...<br>}</pre><p>Don’t forget to register your provider in config/app.php:</p><pre>&#39;providers&#39; =&gt; [<br>    // ...<br>    App\Providers\MacroServiceProvider::class,<br>],</pre><h3>Testing Your Macros</h3><p>Always test your macros to ensure they work as expected:</p><pre>use Tests\TestCase;<br>use Illuminate\Support\Collection;<br><br>class CollectionMacroTest extends TestCase<br>{<br>    /** @test */<br>    public function it_calculates_statistics_correctly()<br>    {<br>        $stats = collect([1, 2, 3, 4, 5])-&gt;statistics();<br>        <br>        $this-&gt;assertEquals(5, $stats[&#39;count&#39;]);<br>        $this-&gt;assertEquals(1, $stats[&#39;min&#39;]);<br>        $this-&gt;assertEquals(5, $stats[&#39;max&#39;]);<br>        $this-&gt;assertEquals(3, $stats[&#39;mean&#39;]);<br>        $this-&gt;assertEquals(3, $stats[&#39;median&#39;]);<br>    }<br>    <br>    /** @test */<br>    public function it_returns_null_for_empty_collection()<br>    {<br>        $stats = collect([])-&gt;statistics();<br>        <br>        $this-&gt;assertNull($stats);<br>    }<br>}</pre><h3>Performance Considerations</h3><p>While macros are powerful, remember:</p><ol><li><strong>Macros are resolved at runtime</strong> — There’s minimal overhead, but avoid overly complex logic in frequently called macros</li><li><strong>Query builder macros don’t add extra queries</strong> — They’re just query construction helpers</li><li><strong>Cache repeated calculations</strong> — If your macro performs heavy computations, consider caching the results</li></ol><h3>Best Practices</h3><ol><li><strong>Name macros descriptively</strong> — Use clear, action-oriented names like whereRecent instead of wr</li><li><strong>Document your macros</strong> — Add PHPDoc blocks explaining parameters and return values</li><li><strong>Keep them focused</strong> — Each macro should do one thing well</li><li><strong>Make them chainable</strong> — Return $this when appropriate to enable method chaining</li><li><strong>Handle edge cases</strong> — Always validate inputs and handle empty/null values gracefully</li></ol><h3>Conclusion</h3><p>Laravel macros are a powerful tool for writing expressive, reusable code. They help you:</p><ul><li>Eliminate code duplication across your application</li><li>Create domain-specific abstractions that match your business logic</li><li>Make your codebase more readable and maintainable</li><li>Build a shared vocabulary for your development team</li></ul><p>Start small by identifying repeated patterns in your codebase, then gradually build your macro library. Before long, you’ll have a powerful toolkit that makes your Laravel applications more elegant and efficient.</p><p>The examples we’ve covered — from statistical analysis to API responses — demonstrate how macros can solve real business problems while keeping your code clean. Now it’s your turn to identify the patterns in your application and create macros that make your life easier.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1986ddfa6aa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PHP Evolution: From 8.0 to 8.5 — A Developer’s Journey Through Modern Web Development]]></title>
            <link>https://medium.com/@ahmedm3bead/php-evolution-from-8-0-to-8-5-a-developers-journey-through-modern-web-development-d0bae5973441?source=rss-7bad226600ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0bae5973441</guid>
            <dc:creator><![CDATA[Ahmed Ebead]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 09:10:38 GMT</pubDate>
            <atom:updated>2025-09-25T09:10:38.110Z</atom:updated>
            <content:encoded><![CDATA[<h3>PHP Evolution: From 8.0 to 8.5 — A Developer’s Journey Through Modern Web Development</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DP9DuiuBwOR4uTHNygAz7Q.png" /></figure><h4><em>How PHP transformed from a simple scripting language into a powerhouse of modern web development</em></h4><p>PHP has come a long way since its humble beginnings as “Personal Home Page” in 1995. Today, it powers over 77% of websites whose server-side programming language is known, including giants like Facebook, WordPress, and Wikipedia. The journey from PHP 8.0 to the latest 8.5 represents one of the most significant evolutionary leaps in the language’s history.</p><h3>Why PHP Still Matters in 2025</h3><p>Before diving into the technical improvements, it’s worth understanding why PHP remains relevant in an ecosystem filled with Node.js, Python, and Go. PHP offers:</p><ul><li><strong>Simplicity and ease of learning</strong> — Perfect for beginners and rapid prototyping</li><li><strong>Massive ecosystem</strong> — Frameworks like Laravel, Symfony, and CodeIgniter</li><li><strong>Cost-effective hosting</strong> — Shared hosting providers universally support PHP</li><li><strong>Strong community</strong> — Decades of collective knowledge and resources</li><li><strong>Performance improvements</strong> — Modern PHP is significantly faster than its predecessors</li></ul><h3>PHP 8.0: The Game Changer (Released November 2020)</h3><p>PHP 8.0 marked a watershed moment with revolutionary features that modernized the language fundamentally.</p><h3>Just-In-Time (JIT) Compilation</h3><p>The most significant addition was the JIT compiler, which compiles PHP code to machine code at runtime. This improvement delivered:</p><ul><li><strong>2x performance boost</strong> for CPU-intensive applications</li><li><strong>Better memory usage</strong> for mathematical computations</li><li><strong>Improved scalability</strong> for high-traffic applications</li></ul><pre>// JIT particularly benefits mathematical operations<br>function fibonacci($n) {<br>    if ($n &lt;= 1) return $n;<br>    return fibonacci($n - 1) + fibonacci($n - 2);<br>}<br>// This runs significantly faster with JIT enabled<br>echo fibonacci(40);</pre><h3>Named Arguments</h3><p>Named arguments revolutionized function calls by allowing parameters to be passed by name rather than position:</p><pre>// Before PHP 8.0<br><br>htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, &#39;UTF-8&#39;, false);// PHP 8.0 and later - much more readable<br>htmlspecialchars(<br>    string: $string,<br>    flags: ENT_COMPAT | ENT_HTML401,<br>    encoding: &#39;UTF-8&#39;,<br>    double_encode: false<br>);</pre><h3>Union Types</h3><p>Union types allow variables to accept multiple types, improving type safety:</p><pre>function processId(int|string $id): string {<br>    return &quot;Processing ID: &quot; . $id;<br>}<br>processId(123);        // Valid<br>processId(&quot;ABC123&quot;);   // Also valid<br>processId(12.5);       // TypeError</pre><h3>Match Expression</h3><p>A more powerful alternative to switch statements:</p><pre>$status = match($code) {<br>    200, 201, 202 =&gt; &#39;Success&#39;,<br>    400, 404 =&gt; &#39;Client Error&#39;,<br>    500, 502, 503 =&gt; &#39;Server Error&#39;,<br>    default =&gt; &#39;Unknown Status&#39;<br>};</pre><h3>Nullsafe Operator</h3><p>Chain method calls safely without worrying about null values:</p><pre>// Before PHP 8.0<br>$country = null;<br>if ($user !== null &amp;&amp; $user-&gt;getAddress() !== null) {<br>    $country = $user-&gt;getAddress()-&gt;getCountry();<br>}<br>// PHP 8.0+<br>$country = $user?-&gt;getAddress()?-&gt;getCountry();</pre><h3>Constructor Property Promotion</h3><p>Dramatically reduce boilerplate code in class constructors:</p><pre>// Before PHP 8.0<br>class User {<br>    private string $name;<br>    private string $email;<br>    private int $age;<br>    <br>    public function __construct(string $name, string $email, int $age) {<br>        $this-&gt;name = $name;<br>        $this-&gt;email = $email;<br>        $this-&gt;age = $age;<br>    }<br>}<br>// PHP 8.0+<br>class User {<br>    public function __construct(<br>        private string $name,<br>        private string $email,<br>        private int $age<br>    ) {}<br>}</pre><h3>Attributes</h3><p>PHP’s answer to annotations, providing metadata for classes, methods, and properties:</p><pre>#[Route(&#39;/api/users&#39;, methods: [&#39;GET&#39;])]<br>class UserController {<br>    #[Deprecated(&#39;Use getUserById instead&#39;)]<br>    public function getUser(): User {<br>        // Implementation<br>    }<br>}</pre><h3>PHP 8.1: Refining Excellence (Released November 2021)</h3><h3>Enums</h3><p>Native enumeration support brought type safety to constants:</p><pre>enum Status: string {<br>    case PENDING = &#39;pending&#39;;<br>    case APPROVED = &#39;approved&#39;;<br>    case REJECTED = &#39;rejected&#39;;<br>    <br>    public function getColor(): string {<br>        return match($this) {<br>            Status::PENDING =&gt; &#39;yellow&#39;,<br>            Status::APPROVED =&gt; &#39;green&#39;,<br>            Status::REJECTED =&gt; &#39;red&#39;,<br>        };<br>    }<br>}<br>$userStatus = Status::PENDING;<br>echo $userStatus-&gt;getColor(); // yellow</pre><h3>Readonly Properties</h3><p>Immutable properties that can only be written once:</p><pre>class User {<br>    public function __construct(<br>        public readonly string $id,<br>        public readonly string $email<br>    ) {}<br>}<br>$user = new User(&#39;123&#39;, &#39;john@example.com&#39;);<br>// $user-&gt;id = &#39;456&#39;; // Fatal error: Cannot modify readonly property</pre><h3>Intersection Types</h3><p>Combine multiple type constraints:</p><pre>function process(Countable&amp;Iterator $collection): void {<br>    // $collection must implement both Countable and Iterator<br>    echo &quot;Processing &quot; . count($collection) . &quot; items&quot;;<br>}</pre><h3>Fibers</h3><p>Cooperative multitasking for better asynchronous programming:</p><pre>$fiber = new Fiber(function (): void {<br>    echo &quot;Fiber started\n&quot;;<br>    Fiber::suspend();<br>    echo &quot;Fiber resumed\n&quot;;<br>});<br>$fiber-&gt;start();<br>echo &quot;Main execution\n&quot;;<br>$fiber-&gt;resume();</pre><h3>PHP 8.2: Performance and Developer Experience (Released December 2022)</h3><h3>Disjunctive Normal Form (DNF) Types</h3><p>Complex type combinations for advanced use cases:</p><pre>function process((A&amp;B)|null $param): void {<br>    // Parameter must be both A and B, or null<br>}</pre><h3>New Random Extension</h3><p>Cryptographically secure random number generation:</p><pre>$randomizer = new Random\Randomizer();<br>$randomBytes = $randomizer-&gt;getBytes(16);<br>$randomInt = $randomizer-&gt;getInt(1, 100);</pre><h3>Readonly Classes</h3><p>Entire classes can now be marked as readonly:</p><pre>readonly class Configuration {<br>    public function __construct(<br>        public string $host,<br>        public int $port,<br>        public string $database<br>    ) {}<br>}</pre><h3>Constants in Traits</h3><p>Traits can now define constants:</p><pre>trait Debuggable {<br>    public const DEBUG_MODE = true;<br>    <br>    public function debug($message): void {<br>        if (self::DEBUG_MODE) {<br>            echo &quot;[DEBUG] $message\n&quot;;<br>        }<br>    }<br>}</pre><h3>PHP 8.3: Stability and Refinement (Released November 2023)</h3><h3>Typed Class Constants</h3><p>Add type declarations to class constants:</p><pre>class MathConstants {<br>    public const float PI = 3.14159;<br>    public const array FIBONACCI = [1, 1, 2, 3, 5, 8];<br>}</pre><h3>Dynamic Class Constant Access</h3><p>Access constants dynamically with improved syntax:</p><pre>class Status {<br>    public const ACTIVE = &#39;active&#39;;<br>    public const INACTIVE = &#39;inactive&#39;;<br>}<br>$status = &#39;ACTIVE&#39;;<br>echo Status::{$status}; // &#39;active&#39;</pre><h3>Anonymous Readonly Classes</h3><p>Create immutable anonymous classes:</p><pre>$config = new readonly class(&#39;localhost&#39;, 3306) {<br>    public function __construct(<br>        public string $host,<br>        public int $port<br>    ) {}<br>};</pre><h3>Override Attribute</h3><p>Explicitly mark method overrides:</p><pre>class Child extends Parent {<br>    #[\Override]<br>    public function process(): void {<br>        // Ensures this method exists in parent class<br>    }<br>}</pre><h3>PHP 8.4: Modern Language Features (Released November 2024)</h3><h3>Property Hooks</h3><p>Getters and setters without the boilerplate:</p><pre>class User {<br>    private string $_name;<br>    <br>    public string $name {<br>        get =&gt; $this-&gt;_name;<br>        set =&gt; $this-&gt;_name = strtoupper($value);<br>    }<br>    <br>    public string $email {<br>        set(string $value) {<br>            if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {<br>                throw new InvalidArgumentException(&#39;Invalid email&#39;);<br>            }<br>            $this-&gt;email = $value;<br>        }<br>    }<br>}<br>$user = new User();<br>$user-&gt;name = &#39;john&#39;; // Automatically converted to &#39;JOHN&#39;</pre><h3>Asymmetric Visibility</h3><p>Different visibility levels for reading and writing:</p><pre>class BankAccount {<br>    public private(set) float $balance = 0.0;<br>    <br>    public function deposit(float $amount): void {<br>        $this-&gt;balance += $amount; // Can write internally<br>    }<br>}<br>$account = new BankAccount();<br>echo $account-&gt;balance; // Can read<br>// $account-&gt;balance = 1000; // Cannot write from outside</pre><h3>New Array Functions</h3><p>Enhanced array manipulation capabilities:</p><pre>// array_find - find first matching element<br>$users = [<br>    [&#39;name&#39; =&gt; &#39;John&#39;, &#39;age&#39; =&gt; 25],<br>    [&#39;name&#39; =&gt; &#39;Jane&#39;, &#39;age&#39; =&gt; 30]<br>];<br>$adult = array_find($users, fn($user) =&gt; $user[&#39;age&#39;] &gt;= 25);<br>// array_find_key - find key of first matching element<br>$key = array_find_key($users, fn($user) =&gt; $user[&#39;name&#39;] === &#39;Jane&#39;);<br>// array_any and array_all<br>$hasAdults = array_any($users, fn($user) =&gt; $user[&#39;age&#39;] &gt;= 18);<br>$allAdults = array_all($users, fn($user) =&gt; $user[&#39;age&#39;] &gt;= 18);</pre><h3>PHP 8.5: The Latest Evolution (Released November 2025)</h3><h3>Generic Support (Preliminary)</h3><p>Basic generic type support for better type safety:</p><pre>/**<br> * @template T<br> */<br>class Collection {<br>    /** @var array&lt;T&gt; */<br>    private array $items = [];<br>    <br>    /** @param T $item */<br>    public function add($item): void {<br>        $this-&gt;items[] = $item;<br>    }<br>    <br>    /** @return T|null */<br>    public function first() {<br>        return $this-&gt;items[0] ?? null;<br>    }<br>}<br>$userCollection = new Collection(); // Collection&lt;User&gt;<br>$userCollection-&gt;add(new User());</pre><h3>Pattern Matching</h3><p>Advanced pattern matching capabilities:</p><pre>function processValue($value) {<br>    return match($value) {<br>        int $x when $x &gt; 0 =&gt; &quot;Positive integer: $x&quot;,<br>        string $s when strlen($s) &gt; 10 =&gt; &quot;Long string&quot;,<br>        array [...$items] when count($items) &gt; 5 =&gt; &quot;Large array&quot;,<br>        default =&gt; &quot;Other value&quot;<br>    };<br>}</pre><h3>Improved Error Handling</h3><p>Better error context and stack traces:</p><pre>try {<br>    riskyOperation();<br>} catch (DatabaseException $e) {<br>    // Enhanced error information with context<br>    logger()-&gt;error(&#39;Database operation failed&#39;, [<br>        &#39;context&#39; =&gt; $e-&gt;getContext(),<br>        &#39;query&#39; =&gt; $e-&gt;getQuery(),<br>        &#39;parameters&#39; =&gt; $e-&gt;getParameters()<br>    ]);<br>}</pre><h3>Multi-line String Literals</h3><p>Heredoc improvements for better code organization:</p><pre>$query = &lt;&lt;&lt;SQL<br>    SELECT u.name, u.email, p.title<br>    FROM users u<br>    JOIN posts p ON u.id = p.user_id<br>    WHERE u.active = true<br>    ORDER BY p.created_at DESC<br>    SQL;</pre><h3>Performance Improvements Across Versions</h3><p>The evolution from PHP 8.0 to 8.5 brought significant performance gains:</p><ul><li><strong>JIT compilation</strong> (8.0): 2x performance for CPU-intensive tasks</li><li><strong>Opcache improvements</strong> (8.1–8.5): Better memory usage and faster execution</li><li><strong>String handling optimizations</strong> (8.2+): Reduced memory allocations</li><li><strong>Array operations</strong> (8.4+): Faster array manipulation functions</li><li><strong>Type system enhancements</strong> (8.0–8.5): Better optimization opportunities</li></ul><h3>Migration Considerations</h3><h3>Breaking Changes to Watch</h3><p>Each version introduced some breaking changes:</p><ul><li><strong>PHP 8.0</strong>: Resource to object migrations, stricter type checking</li><li><strong>PHP 8.1</strong>: Passing null to non-nullable parameters</li><li><strong>PHP 8.2</strong>: Dynamic properties deprecation</li><li><strong>PHP 8.3</strong>: Passing incorrect types to internal functions</li><li><strong>PHP 8.4</strong>: Implicit nullable parameter types deprecation</li></ul><h3>Upgrade Strategy</h3><ol><li><strong>Test thoroughly</strong> — Use automated testing suites</li><li><strong>Update dependencies</strong> — Ensure framework compatibility</li><li><strong>Review deprecations</strong> — Address warnings proactively</li><li><strong>Performance testing</strong> — Benchmark before and after</li><li><strong>Staged rollout</strong> — Deploy to production gradually</li></ol><h3>The Impact on Modern Web Development</h3><h3>Framework Evolution</h3><p>Popular PHP frameworks evolved alongside the language:</p><ul><li><strong>Laravel 11</strong> leverages PHP 8.2+ features extensively</li><li><strong>Symfony 7</strong> uses enums, readonly properties, and union types</li><li><strong>CodeIgniter 4</strong> embraces modern PHP practices</li></ul><h3>Developer Productivity</h3><p>Modern PHP features dramatically improved developer experience:</p><ul><li><strong>Reduced boilerplate</strong> with property promotion and readonly classes</li><li><strong>Better IDE support</strong> through improved type system</li><li><strong>Easier debugging</strong> with enhanced error handling</li><li><strong>Cleaner code</strong> using match expressions and nullsafe operators</li></ul><h3>Community Growth</h3><p>The PHP community has grown stronger:</p><ul><li><strong>Active development</strong> with annual releases</li><li><strong>Strong governance</strong> through the PHP Foundation</li><li><strong>Improved documentation</strong> and learning resources</li><li><strong>Modern tooling</strong> like Composer, PHPStan, and Rector</li></ul><h3>Looking Forward: The Future of PHP</h3><p>PHP’s roadmap includes exciting developments:</p><ul><li><strong>Full generic support</strong> for type-safe collections</li><li><strong>Improved async programming</strong> building on Fibers</li><li><strong>Better tooling integration</strong> for development workflows</li><li><strong>Performance optimizations</strong> continuing the speed improvements</li><li><strong>Modern syntax additions</strong> keeping PHP competitive</li></ul><h3>Conclusion</h3><p>The journey from PHP 8.0 to 8.5 represents more than just version updates — it’s a complete transformation of PHP into a modern, type-safe, and performant language. Features like JIT compilation, union types, enums, property hooks, and preliminary generic support have positioned PHP as a serious contender in the modern web development landscape.</p><p>For developers still using older PHP versions, the upgrade path offers compelling benefits: better performance, improved code safety, enhanced developer experience, and access to modern language features that make code more maintainable and expressive.</p><p>PHP’s evolution demonstrates that established languages can reinvent themselves while maintaining their core strengths. As we look toward the future, PHP continues to prove that it’s not just surviving in the modern web development ecosystem — it’s thriving.</p><p>Whether you’re building the next unicorn startup or maintaining enterprise applications, modern PHP provides the tools, performance, and developer experience needed to succeed in today’s competitive landscape.</p><p><em>Ready to start your PHP 8.5 journey? The best time to upgrade was yesterday. The second-best time is now.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0bae5973441" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Pipelines: The Ultimate Guide to Clean, Modular Code]]></title>
            <link>https://medium.com/@ahmedm3bead/laravel-pipelines-the-ultimate-guide-to-clean-modular-code-c01e30c6c5c4?source=rss-7bad226600ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/c01e30c6c5c4</guid>
            <category><![CDATA[laravel-pipeline]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Ahmed Ebead]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 14:35:24 GMT</pubDate>
            <atom:updated>2025-09-21T14:35:24.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kfNpX-R1AhrRdr6RZOkV4g.png" /></figure><h3>Laravel Pipelines: The Ultimate Guide to Clean, Modular Code</h3><p>Laravel’s Pipeline pattern is one of the framework’s most elegant yet underused features. It provides a clean, maintainable way to pass data through a series of operations, transforming it step by step. If you’ve ever found yourself writing deeply nested if-else statements or chaining multiple operations together, pipelines might be exactly what you need.</p><h3>What Are Laravel Pipelines?</h3><p>Think of a pipeline as an assembly line in a factory. Your data enters at one end and passes through various stations (pipes), where each station performs a specific operation. At the end, you get your processed result.</p><p>In Laravel, pipelines allow you to:</p><ul><li>Break complex operations into smaller, testable units</li><li>Maintain clean separation of concerns</li><li>Create reusable processing steps</li><li>Write more readable and maintainable code</li></ul><h3>The Anatomy of a Pipeline</h3><p>Every Laravel pipeline consists of three main components:</p><ol><li><strong>The Passable</strong>: The data that flows through the pipeline</li><li><strong>The Pipes</strong>: Individual classes that process the data</li><li><strong>The Destination</strong>: The final callback that handles the processed data</li></ol><p>php</p><pre>use Illuminate\Pipeline\Pipeline;<br><br>$result = app(Pipeline::class)<br>    -&gt;send($data)           // The passable<br>    -&gt;through([             // The pipes<br>        FirstPipe::class,<br>        SecondPipe::class,<br>        ThirdPipe::class,<br>    ])<br>    -&gt;then(function ($data) { // The destination<br>        return $data;<br>    });</pre><h3>Creating Your First Pipeline</h3><p>Let’s build a practical example: a user registration pipeline that validates, sanitizes, and processes user data.</p><h3>Step 1: Create the Pipe Classes</h3><p>Each pipe should implement a handle method that receives the passable data and a closure to continue to the next pipe:</p><p>php</p><pre>&lt;?php<br><br>namespace App\Pipes\UserRegistration;<br>class ValidateUserData<br>{<br>    public function handle($data, $next)<br>    {<br>        // Perform validation<br>        $validator = validator($data, [<br>            &#39;email&#39; =&gt; &#39;required|email|unique:users&#39;,<br>            &#39;password&#39; =&gt; &#39;required|min:8&#39;,<br>            &#39;name&#39; =&gt; &#39;required|string|max:255&#39;,<br>        ]);<br>        if ($validator-&gt;fails()) {<br>            throw new ValidationException($validator);<br>        }<br>        return $next($data);<br>    }<br>}</pre><pre>&lt;?php<br><br>namespace App\Pipes\UserRegistration;<br>class SanitizeUserData<br>{<br>    public function handle($data, $next)<br>    {<br>        $data[&#39;name&#39;] = trim(strip_tags($data[&#39;name&#39;]));<br>        $data[&#39;email&#39;] = strtolower(trim($data[&#39;email&#39;]));<br>        <br>        return $next($data);<br>    }<br>}</pre><pre>&lt;?php<br><br>namespace App\Pipes\UserRegistration;<br>use Illuminate\Support\Facades\Hash;<br>class HashPassword<br>{<br>    public function handle($data, $next)<br>    {<br>        $data[&#39;password&#39;] = Hash::make($data[&#39;password&#39;]);<br>        <br>        return $next($data);<br>    }<br>}</pre><h3>Step 2: Use the Pipeline</h3><p>Now, let’s use our pipeline in a controller:</p><pre>&lt;?php<br>namespace App\Http\Controllers;<br><br>use App\Models\User;<br>use Illuminate\Http\Request;<br>use Illuminate\Pipeline\Pipeline;<br>use App\Pipes\UserRegistration\ValidateUserData;<br>use App\Pipes\UserRegistration\SanitizeUserData;<br>use App\Pipes\UserRegistration\HashPassword;<br>class UserController extends Controller<br>{<br>    public function register(Request $request)<br>    {<br>        $userData = app(Pipeline::class)<br>            -&gt;send($request-&gt;all())<br>            -&gt;through([<br>                ValidateUserData::class,<br>                SanitizeUserData::class,<br>                HashPassword::class,<br>            ])<br>            -&gt;then(function ($data) {<br>                return User::create($data);<br>            });<br>        return response()-&gt;json([<br>            &#39;message&#39; =&gt; &#39;User created successfully&#39;,<br>            &#39;user&#39; =&gt; $userData<br>        ], 201);<br>    }<br>}</pre><h3>Advanced Pipeline Techniques</h3><h3>Using Via Method for Custom Method Names</h3><p>If you don’t want to use the default handle method, you can specify a custom method using via:</p><pre>$result = app(Pipeline::class)<br>    -&gt;send($data)<br>    -&gt;through([<br>        ProcessPayment::class,<br>        SendNotification::class,<br>    ])<br>    -&gt;via(&#39;execute&#39;)  // Use &#39;execute&#39; instead of &#39;handle&#39;<br>    -&gt;then(function ($data) {<br>        return $data;<br>    });</pre><h3>Conditional Pipes</h3><p>You can conditionally add pipes to your pipeline:</p><pre>$pipes = [<br>    ValidateData::class,<br>    SanitizeData::class,<br>];<br><br>if ($shouldHashPassword) {<br>    $pipes[] = HashPassword::class;<br>}<br>$result = app(Pipeline::class)<br>    -&gt;send($data)<br>    -&gt;through($pipes)<br>    -&gt;then(function ($data) {<br>        return $data;<br>    });</pre><h3>Pipeline with Parameters</h3><p>Sometimes you need to pass additional parameters to your pipes:</p><pre>class EncryptData<br>{<br>    public function handle($data, $next, $algorithm = &#39;AES-256-CBC&#39;)<br>    {<br>        $data[&#39;encrypted&#39;] = encrypt($data[&#39;sensitive_info&#39;], $algorithm);<br>        unset($data[&#39;sensitive_info&#39;]);<br>        <br>        return $next($data);<br>    }<br>}<br>// Usage<br>$result = app(Pipeline::class)<br>    -&gt;send($data)<br>    -&gt;through([<br>        EncryptData::class . &#39;:AES-128-CBC&#39;<br>    ])<br>    -&gt;then(function ($data) {<br>        return $data;<br>    });</pre><h3>Real-World Examples</h3><h3>Image Processing Pipeline</h3><p>Here’s a practical example for processing uploaded images:</p><pre>namespace App\Pipes\ImageProcessing;<br><br>class ValidateImage<br>{<br>    public function handle($image, $next)<br>    {<br>        if (!$image-&gt;isValid()) {<br>            throw new InvalidImageException(&#39;Invalid image file&#39;);<br>        }<br>        <br>        return $next($image);<br>    }<br>}<br>class ResizeImage<br>{<br>    public function handle($image, $next)<br>    {<br>        $resized = Image::make($image)-&gt;resize(800, 600);<br>        <br>        return $next($resized);<br>    }<br>}<br>class OptimizeImage<br>{<br>    public function handle($image, $next)<br>    {<br>        $image-&gt;quality(85);<br>        <br>        return $next($image);<br>    }<br>}<br>// In your controller<br>public function uploadImage(Request $request)<br>{<br>    $processedImage = app(Pipeline::class)<br>        -&gt;send($request-&gt;file(&#39;image&#39;))<br>        -&gt;through([<br>            ValidateImage::class,<br>            ResizeImage::class,<br>            OptimizeImage::class,<br>        ])<br>        -&gt;then(function ($image) {<br>            $filename = uniqid() . &#39;.jpg&#39;;<br>            $image-&gt;save(storage_path(&#39;app/public/images/&#39; . $filename));<br>            return $filename;<br>        });<br>    return response()-&gt;json([&#39;filename&#39; =&gt; $processedImage]);<br>}</pre><h3>API Response Pipeline</h3><p>Transform your API responses consistently:</p><pre>namespace App\Pipes\ApiResponse;<br><br>class AddTimestamp<br>{<br>    public function handle($data, $next)<br>    {<br>        $data[&#39;timestamp&#39;] = now()-&gt;toISOString();<br>        <br>        return $next($data);<br>    }<br>}<br>class AddMetadata<br>{<br>    public function handle($data, $next)<br>    {<br>        $data[&#39;meta&#39;] = [<br>            &#39;version&#39; =&gt; config(&#39;app.version&#39;),<br>            &#39;environment&#39; =&gt; config(&#39;app.env&#39;),<br>        ];<br>        <br>        return $next($data);<br>    }<br>}<br>class FormatResponse<br>{<br>    public function handle($data, $next)<br>    {<br>        return $next([<br>            &#39;success&#39; =&gt; true,<br>            &#39;data&#39; =&gt; $data,<br>        ]);<br>    }<br>}</pre><h3>Testing Pipelines</h3><p>One of the biggest advantages of pipelines is how easy they are to test. You can test each pipe independently:</p><p>php</p><pre>&lt;?php<br>namespace Tests\Unit\Pipes;<br><br>use Tests\TestCase;<br>use App\Pipes\UserRegistration\HashPassword;<br>class HashPasswordTest extends TestCase<br>{<br>    public function test_it_hashes_password()<br>    {<br>        $pipe = new HashPassword();<br>        $data = [&#39;password&#39; =&gt; &#39;plaintext&#39;];<br>        <br>        $result = $pipe-&gt;handle($data, function ($data) {<br>            return $data;<br>        });<br>        <br>        $this-&gt;assertNotEquals(&#39;plaintext&#39;, $result[&#39;password&#39;]);<br>        $this-&gt;assertTrue(Hash::check(&#39;plaintext&#39;, $result[&#39;password&#39;]));<br>    }<br>}</pre><h3>When to Use Pipelines</h3><p>Pipelines are perfect for scenarios where you have:</p><ul><li><strong>Sequential data processing</strong>: When data needs to go through multiple transformation steps</li><li><strong>Complex validation</strong>: Multi-step validation processes with different rules</li><li><strong>API middleware-like operations</strong>: When you need to apply multiple operations to requests or responses</li><li><strong>Data import/export</strong>: Processing data through multiple cleaning and transformation steps</li><li><strong>Order processing</strong>: E-commerce workflows with multiple steps (validation, inventory check, payment, fulfillment)</li></ul><h3>Best Practices</h3><ol><li><strong>Keep pipes single-purpose</strong>: Each pipe should do one thing well</li><li><strong>Make pipes stateless</strong>: Don’t store data in pipe properties</li><li><strong>Handle errors gracefully</strong>: Use proper exception handling in your pipes</li><li><strong>Use meaningful names</strong>: Pipe class names should clearly describe their purpose</li><li><strong>Test extensively</strong>: Each pipe should have comprehensive unit tests</li><li><strong>Document complex pipelines</strong>: Add comments explaining the flow for complex processes</li></ol><h3>Performance Considerations</h3><p>While pipelines add a small overhead due to the additional method calls and object instantiation, the benefits usually outweigh the costs. However, for extremely high-performance scenarios, consider:</p><ul><li>Using simple function calls instead of classes for very basic operations</li><li>Caching pipe instances when processing large datasets</li><li>Profiling your pipeline to identify bottlenecks</li></ul><h3>Conclusion</h3><p>Laravel Pipelines offer a powerful way to write clean, maintainable, and testable code. They shine in scenarios where you have complex, multi-step processes that need to be broken down into manageable pieces.</p><p>By embracing the pipeline pattern, you’ll find your code becomes more modular, easier to test, and much more readable. The next time you find yourself writing complex nested logic or chaining multiple operations together, consider whether a pipeline might be the elegant solution you’re looking for.</p><p>Start small with a simple pipeline, and as you become more comfortable with the pattern, you’ll discover countless opportunities to apply this powerful architectural tool in your Laravel applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c01e30c6c5c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ NativePHP July 2025: Building Better Desktop Apps with Laravel Just Got Easier]]></title>
            <link>https://medium.com/@ahmedm3bead/nativephp-july-2025-building-better-desktop-apps-with-laravel-just-got-easier-268911a12052?source=rss-7bad226600ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/268911a12052</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[desktop-app]]></category>
            <dc:creator><![CDATA[Ahmed Ebead]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 13:18:20 GMT</pubDate>
            <atom:updated>2025-08-12T13:18:20.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*82ODwpSzkMIMS6N5" /></figure><h3>The desktop development landscape for PHP developers is evolving, and NativePHP is leading the charge</h3><p>If you’re a Laravel developer who’s ever dreamed of building native desktop applications without learning a completely new tech stack, this update is for you. NativePHP just dropped significant updates that make desktop development more accessible, secure, and powerful than ever before.</p><h3>What’s NativePHP?</h3><p>For the uninitiated, NativePHP is a game-changing framework that lets you build cross-platform desktop applications using the Laravel framework you already know and love. Think Electron, but specifically tailored for PHP developers. No need to learn Swift for macOS, C# for Windows, or wrestle with complex native APIs — just write Laravel code and ship to all platforms.</p><h3>🎯 The Big Updates (July 2025)</h3><h3>1. Enterprise-Ready with Azure Trusted Signing</h3><p>One of the most significant additions is <strong>Azure Trusted Signing support</strong>. If you’ve ever tried distributing Windows applications, you know the pain of dealing with SmartScreen warnings and untrusted publisher alerts.</p><p>With this update, you can now:</p><ul><li>Sign your Windows applications using Azure’s trusted certificates</li><li>Eliminate those scary security warnings for your users</li><li>Build enterprise-grade applications that IT departments will actually approve</li></ul><p>This is huge for anyone building B2B desktop applications or internal enterprise tools.</p><h3>2. Advanced Printing Capabilities</h3><p>The new printing API enhancements give you granular control over document output:</p><pre>// Before: Basic printing<br>$window-&gt;print();<br>// Now: Full control<br>$window-&gt;print([<br>    &#39;margins&#39; =&gt; &#39;custom&#39;,<br>    &#39;landscape&#39; =&gt; true,<br>    &#39;copies&#39; =&gt; 2,<br>    &#39;pageRanges&#39; =&gt; &#39;1-3, 5&#39;,<br>    // ... and many more options<br>]);</pre><p>Perfect for applications that need to generate reports, invoices, or any printable documents with specific formatting requirements.</p><h3>3. Stealth Mode: New Window Management Options</h3><p>Sometimes you need your application to be more… discrete. The new window management properties let you:</p><ul><li><strong>skipTaskbar</strong>: Keep your app window off the taskbar (Windows/Linux)</li><li><strong>hiddenInMissionControl</strong>: Hide from Mission Control (macOS)</li></ul><p>These are game-changers for:</p><ul><li>System tray applications</li><li>Background utilities</li><li>Overlay tools</li><li>Focus apps that shouldn’t clutter the user’s workspace</li></ul><h3>4. Laravel 12.21+ Full Compatibility</h3><p>The team worked hard to ensure compatibility with the latest Laravel versions. They’ve added the mbregex extension support and updated to the latest PHP 8.3 and 8.4 builds. This means you can use all the latest Laravel features in your desktop apps without compromise.</p><h3>🔧 Critical Bug Fixes That Matter</h3><h3>Windows Deep Links Are Finally Stable</h3><p>Deep linking on Windows was causing crashes — a critical issue for apps that need to handle custom protocols or OAuth callbacks. This is now fixed, making authentication flows and inter-app communication reliable across all platforms.</p><h3>Mac Notarization Improvements</h3><p>The build process for macOS is now smarter, only triggering notarization hooks when actually building for Mac. This speeds up development cycles when testing on other platforms.</p><h3>Auto-Update Intelligence</h3><p>The auto-updater no longer creates unnecessary files when disabled, keeping your app bundle cleaner and reducing potential confusion.</p><h3>💡 Why This Matters for PHP Developers</h3><h3>1. One Codebase, All Platforms</h3><p>Write your application logic once in Laravel and deploy to Windows, macOS, and Linux. No platform-specific rewrites needed.</p><h3>2. Familiar Territory</h3><p>Use the Laravel ecosystem you already know — Eloquent, Blade templates, Laravel’s validation, queues, and more — in desktop applications.</p><h3>3. Rapid Development</h3><p>Building a desktop app is now as fast as building a web app. Use Laravel’s rapid development features like migrations, seeders, and artisan commands in your desktop applications.</p><h3>4. Professional Distribution</h3><p>With Azure signing support and improved notarization, your apps look professional from download to installation.</p><h3>🚀 Getting Started or Upgrading</h3><p>If you’re already using NativePHP, upgrading is as simple as:</p><p>bash</p><pre>composer update</pre><p>For newcomers, getting started with NativePHP is straightforward:</p><pre># Install Laravel<br>composer create-project laravel/laravel my-desktop-app<br># Add NativePHP<br>cd my-desktop-app<br>composer require nativephp/electron<br># Start building!<br>php artisan native:serve</pre><h3>🌟 Real-World Use Cases</h3><p>With these updates, NativePHP is perfect for:</p><ul><li><strong>Database management tools</strong> with advanced printing for reports</li><li><strong>Point of Sale (POS) systems</strong> that need trusted signing for enterprise deployment</li><li><strong>Development tools</strong> that integrate with system services</li><li><strong>Content creation apps</strong> with sophisticated document handling</li><li><strong>Internal enterprise applications</strong> that need to pass IT security requirements</li></ul><h3>🤝 Community and Open Source</h3><p>NativePHP remains free and open source, driven by community contributions. Special recognition goes to contributors like @WINBIGFOX and @faustbrian who implemented many of these features. The project welcomes both code contributions and sponsorships to ensure its continued development.</p><h3>🎯 The Bottom Line</h3><p>This update isn’t just about new features — it’s about making desktop development accessible to the massive PHP developer community. Whether you’re building internal tools for your company, creating the next great productivity app, or just experimenting with desktop development, NativePHP removes the barriers that traditionally kept PHP developers from the desktop space.</p><p>The combination of enterprise features (Azure signing), practical enhancements (printing, window management), and rock-solid stability (bug fixes, Laravel compatibility) makes this a watershed moment for PHP desktop development.</p><h3>What’s Next?</h3><p>The NativePHP team shows no signs of slowing down. With Laravel’s continued evolution and the growing demand for desktop applications that work seamlessly with web services, NativePHP is positioned to become the go-to solution for PHP developers venturing into desktop development.</p><p>Ready to build your first desktop app with Laravel? The tools are better than ever, the community is growing, and the possibilities are endless.</p><p><strong>Happy building! 🚀</strong></p><p><em>Want to learn more? Check out the </em><a href="https://nativephp.com/"><em>NativePHP documentation</em></a><em> and join the community. Have you built something cool with NativePHP? Share it in the comments below!</em></p><p>#NativePHP #Laravel #DesktopDevelopment #PHP #ElectronAlternative #CrossPlatform #OpenSource</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=268911a12052" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>