<?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 Dominik on Medium]]></title>
        <description><![CDATA[Stories by Dominik on Medium]]></description>
        <link>https://medium.com/@Dommin?source=rss-be410870b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2MP8r3wLzL75i3SL</url>
            <title>Stories by Dominik on Medium</title>
            <link>https://medium.com/@Dommin?source=rss-be410870b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:08:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Dommin/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[Secure your Laravel App: OWASP Top 10 + Beyond]]></title>
            <link>https://levelup.gitconnected.com/secure-your-laravel-app-owasp-top-10-beyond-a10f823621f0?source=rss-be410870b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a10f823621f0</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dominik]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 08:36:07 GMT</pubDate>
            <atom:updated>2025-07-30T03:37:45.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FrK9lD0LxjIR7xQvn44dg.png" /></figure><blockquote><em>Laravel is fast, powerful, and elegant — but are your apps secure?</em></blockquote><p>Whether you’re a junior developer or a solo builder shipping Laravel + Inertia.js apps, understanding the <a href="https://owasp.org/Top10/">OWASP Top 10</a> and other real-world security flaws is essential.</p><p>This guide will walk you through:</p><ul><li>✅ OWASP Top 10 — with real Laravel + React examples</li><li>✅ How to fix each one (Gate, Policy, Middleware, Fortify, Sanctum, etc.)</li><li>✅ Extra vulnerabilities not listed by OWASP (but equally dangerous)</li><li>✅ A final <strong>Laravel Production Security Checklist</strong></li></ul><h3>📚 Table of Contents</h3><ul><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#secure-your-laravel-app-owasp-top-10--beyond">Secure your Laravel App: OWASP Top 10 + Beyond</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#-table-of-contents">📚 Table of Contents</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#what-is-owasp">What is OWASP?</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#owasp-top-10-with-laravel-examples">OWASP Top 10 with Laravel Examples</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#1-broken-access-control-a01">1. Broken Access Control (A01)</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#2-cryptographic-failures-a02">2. Cryptographic Failures (A02)</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#3-injection-a03">3. Injection (A03)</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#4-insecure-design-a04">4. Insecure Design (A04)</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#5-security-misconfiguration-a05">5. Security Misconfiguration (A05)</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#6-vulnerable-components-a06">6. Vulnerable Components (A06)</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#7-identification--authentication-failures-a07">7. Identification &amp; Authentication Failures (A07)</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#8-software-and-data-integrity-failures-a08">8. Software and Data Integrity Failures (A08)</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#9-security-logging--monitoring-failures-a09">9. Security Logging &amp; Monitoring Failures (A09)</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#10-server-side-request-forgery-ssrf-a10">10. Server-Side Request Forgery (SSRF) (A10)</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#beyond-owasp-more-laravel-security-risks">Beyond OWASP: More Laravel Security Risks</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#%EF%B8%8F-1-mass-assignment-vulnerabilities">⚠️ 1. Mass Assignment Vulnerabilities</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#-2-cross-site-scripting-xss">🔎 2. Cross-Site Scripting (XSS)</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#-3-cors-misconfiguration">🌐 3. CORS Misconfiguration</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#-4-session-misconfiguration">🕓 4. Session Misconfiguration</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#%EF%B8%8F-5-open-redirects">🗂️ 5. Open Redirects</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#%EF%B8%8F-6-unsafe-file-uploads">🗄️ 6. Unsafe File Uploads</a></li><li><a href="http://localhost:63342/markdownPreview/1617514641/markdown-preview-index-1363628162.html?_ijt=cpff9dmf5m8oe8s5vup4jt14sj#-7-env-exposure">🛑 7. .env Exposure</a></li></ul><h3>What is OWASP?</h3><p>The Open Web Application Security Project (OWASP) is a nonprofit foundation that works to improve software security. Their flagship project — the <strong>OWASP Top 10</strong> — is a list of the <strong>10 most critical web application security risks</strong>.</p><p>Laravel gives you great tools to prevent most of these out-of-the-box, but you still need to use them correctly.</p><h3>OWASP Top 10 with Laravel Examples</h3><h3>1. Broken Access Control (A01)</h3><p><strong>Problem:</strong> Users access data or functions they shouldn’t.</p><pre>// ❌ Admin route open to all authenticated users<br>Route::get(&#39;/admin/users&#39;, [UserController::class, &#39;index&#39;]);<br><br>// ✅ Use Policy<br>$this-&gt;authorize(&#39;viewAny&#39;, User::class);<br><br>// ✅ Example Policy<br>public function viewAny(User $user)<br>{<br>    return $user-&gt;is_admin;<br>}<br><br>// Or wrap with a Gate:<br>Gate::define(&#39;access-admin-panel&#39;, fn(User $user) =&gt; $user-&gt;is_admin);</pre><p><strong>Tip:</strong> For advanced or reusable access logic, consider creating a custom middleware. In Laravel 12, middleware registration has moved from app/Http/Kernel.php to bootstrap/app.php.</p><p><strong>How to create and register a custom middleware in Laravel 12:</strong></p><ol><li>Create the middleware:</li></ol><pre>php artisan make:middleware EnsureUserIsAdmin</pre><ol><li>Register the middleware alias in bootstrap/app.php:</li></ol><pre>use Illuminate\Foundation\Configuration\Middleware;<br><br>return Application::configure(...)<br>    -&gt;withMiddleware(function (Middleware $middleware) {<br>        $middleware-&gt;alias([<br>            &#39;admin&#39; =&gt; \App\Http\Middleware\EnsureUserIsAdmin::class,<br>        ]);<br>    })<br>    // ...<br>    -&gt;create();</pre><ol><li>Use the middleware alias in your routes or controllers:</li></ol><pre>// In routes/web.php<br>Route::middleware([&#39;admin&#39;])-&gt;group(function () {<br>    Route::get(&#39;/admin/users&#39;, [UserController::class, &#39;index&#39;]);<br>});<br><br>// Or on a single route<br>Route::get(&#39;/admin/dashboard&#39;, [DashboardController::class, &#39;index&#39;])-&gt;middleware(&#39;admin&#39;);<br><br>// Or in a controller constructor<br>public function __construct()<br>{<br>    $this-&gt;middleware(&#39;admin&#39;);<br>}</pre><blockquote><strong><em>Note:</em></strong><em> If you are upgrading from Laravel 10 or earlier, remember that middleware registration is no longer done in </em><em>app/Http/Kernel.php but in </em><em>bootstrap/app.php.</em></blockquote><p><strong>Tips:</strong></p><ul><li>Always use Policies or Gates for sensitive actions.</li><li>Restrict resource routes with middleware(&#39;can:action,model&#39;).</li><li>Never trust client-side checks.</li></ul><h3>2. Cryptographic Failures (A02)</h3><p><strong>Problem:</strong> Sensitive data like passwords or tokens stored insecurely.</p><pre>// ❌ Never store raw password<br>User::create([&#39;password&#39; =&gt; $request-&gt;password]);<br><br>// ✅ Always use hash()<br>use Illuminate\Support\Facades\Hash;<br><br>User::create([<br>    &#39;password&#39; =&gt; Hash::make($request-&gt;password),<br>]);<br><br>// 🔐 Also use Crypt::encryptString() for sensitive data like tokens or API secrets.<br>use Illuminate\Support\Facades\Crypt;<br><br>$encrypted = Crypt::encryptString($token);</pre><p><strong>Best practice:</strong> Instead of manually encrypting and decrypting data, you can use Eloquent Attribute Casting. In Laravel 11 and above, use the casts() method instead of the $casts property:</p><pre>// In your User.php model<br>protected function casts(): array<br>{<br>    return [<br>        &#39;api_token&#39; =&gt; &#39;encrypted&#39;,<br>        &#39;settings&#39; =&gt; &#39;encrypted:array&#39;, // for arrays<br>    ];<br>}</pre><p>This way, Laravel will automatically encrypt and decrypt the field when saving or retrieving it.</p><blockquote><strong><em>Note:</em></strong><em> In Laravel 11+, attribute casting is now defined using the </em><em>casts() method instead of the </em><em>$casts property. This provides more flexibility and clarity in your models. See the official documentation for more advanced usage.</em></blockquote><p><strong>What should you hash or encrypt?</strong></p><ul><li>User passwords (<strong>hash</strong> — always with Hash::make())</li><li>API tokens, refresh tokens (<strong>encrypt</strong> — e.g., with Eloquent cast ‘encrypted’)</li><li>API keys, integration secrets</li><li>Sensitive user data (e.g., SSNs, tax IDs, addresses, if extra protection is required)</li><li>Configuration data that should not be stored in plain text in the database</li></ul><p><strong>Remember:</strong></p><ul><li>Hashing (e.g., for passwords) is one-way — you cannot recover the original value.</li><li>Encryption (e.g., for tokens, secrets) is two-way — you can decrypt the value when needed.</li></ul><h3>3. Injection (A03)</h3><p><strong>Problem:</strong> User input modifies SQL, Shell, or other commands.</p><pre>// ❌ Raw SQL vulnerable to injection<br>DB::select(&quot;SELECT * FROM users WHERE email = &#39;{$email}&#39;&quot;);<br><br>// ✅ Use Query Builder or Eloquent<br>User::where(&#39;email&#39;, $email)-&gt;first();</pre><p><strong>Tips:</strong></p><ul><li>Always validate input with Form Requests.</li><li>Use parameterized queries.</li><li>Escape output in Blade with {{ }} (never use {!! !!} unless sanitized).</li></ul><h3>4. Insecure Design (A04)</h3><p><strong>Problem:</strong> Security missing at the design level.</p><p><strong>Examples:</strong></p><ul><li>Missing rate limiting</li><li>No email verification</li><li>No MFA on account deletion</li></ul><pre>// ✅ Throttle login<br>Route::post(&#39;/login&#39;, [AuthController::class, &#39;login&#39;])-&gt;middleware(&#39;throttle:5,1&#39;);</pre><ul><li>Use Laravel Fortify to enable email verification &amp; 2FA easily.</li><li>Design for least privilege and defense in depth.</li></ul><h3>5. Security Misconfiguration (A05)</h3><p><strong>Problem:</strong> Dangerous settings in production.</p><ul><li>APP_DEBUG=true leaks stack trace</li><li>.env accessible if /public not set as web root</li></ul><p><strong>✅ Fixes:</strong></p><ul><li>APP_DEBUG=false in .env</li><li>Use php artisan config:cache</li><li>Only expose /public via Nginx or Apache</li><li>Set proper permissions on storage and .env</li></ul><h3>6. Vulnerable Components (A06)</h3><p><strong>Problem:</strong> Using outdated or insecure dependencies.</p><p><strong>✅ Run audits regularly:</strong></p><pre>composer audit<br>npm audit fix</pre><ul><li>Pin versions in composer.json and package.json.</li><li>Monitor releases of Laravel, Inertia, Sanctum, etc.</li><li>Remove unused packages.</li></ul><h3>7. Identification &amp; Authentication Failures (A07)</h3><p><strong>Problem:</strong> Broken authentication logic.</p><pre>// ❌ Password not hashed<br>User::create([&#39;password&#39; =&gt; $request-&gt;password]);<br><br>// ✅ Use Fortify for authentication and password reset flows.</pre><ul><li>Enforce strong passwords and password policies.</li><li>Use Laravel’s built-in authentication scaffolding.</li><li>Implement account lockout after failed attempts.</li></ul><h3>8. Software and Data Integrity Failures (A08)</h3><p><strong>Problem:</strong> Tampered files, unsigned assets, broken CI/CD chain.</p><pre>&lt;!-- ❌ Unverified script --&gt;<br>&lt;script src=&quot;https://cdn.example.com/react.js&quot;&gt;&lt;/script&gt;<br><br>&lt;!-- ✅ Use integrity hash --&gt;<br>&lt;script src=&quot;...&quot; integrity=&quot;sha384-...&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;</pre><ul><li>Only use trusted, pinned packages.</li><li>Sign deployment artifacts if possible.</li><li>Use Laravel’s signed URLs for sensitive actions.</li></ul><h3>9. Security Logging &amp; Monitoring Failures (A09)</h3><p><strong>Problem:</strong> You can’t detect or trace suspicious activity.</p><p><strong>✅ Log failed logins, password resets, suspicious behaviors:</strong></p><pre>Log::warning(&#39;Login failed&#39;, [<br>    &#39;email&#39; =&gt; $request-&gt;email,<br>    &#39;ip&#39; =&gt; $request-&gt;ip(),<br>]);</pre><ul><li>Use Laravel Telescope or external tools like Sentry, ELK.</li><li>Set up alerts for suspicious activity.</li><li>Regularly review logs.</li></ul><h3>10. Server-Side Request Forgery (SSRF) (A10)</h3><p><strong>Problem:</strong> App makes server-side request to untrusted user input.</p><pre>// ❌ User-controlled URL<br>Http::get($request-&gt;input(&#39;url&#39;));<br><br>// ✅ Whitelist trusted domains:<br>$request-&gt;validate([<br>    &#39;url&#39; =&gt; &#39;required|url|regex:/^https:\/\/api\.mydomain\.com/&#39;,<br>]);<br><br>Http::get($request-&gt;input(&#39;url&#39;))-&gt;throw();</pre><ul><li>Never fetch arbitrary URLs from user input.</li><li>Use allow-lists and strict validation.</li></ul><h3>Beyond OWASP: More Laravel Security Risks</h3><h3>⚠️ 1. Mass Assignment Vulnerabilities</h3><p><strong>Problem:</strong> Attackers can set any model attribute if you don’t restrict which fields are mass-assignable.</p><pre>// ❌ Dangerous: allows all request fields to be set<br>User::create($request-&gt;all());<br><br>// ✅ Use $fillable to explicitly allow only certain fields<br>class User extends Model {<br>    protected $fillable = [&#39;name&#39;, &#39;email&#39;, &#39;password&#39;];<br>}<br><br>// Or use $guarded to block all except listed fields<br>class User extends Model {<br>    protected $guarded = [&#39;is_admin&#39;, &#39;role&#39;];<br>}<br><br>// ✅ Safer: only pass allowed fields from request<br>User::create($request-&gt;only([&#39;name&#39;, &#39;email&#39;, &#39;password&#39;]));</pre><p><strong>Best Practices:</strong></p><ul><li>Always define $fillable or $guarded in your models.</li><li>Never use $request-&gt;all() for mass assignment.</li><li>Validate input with Form Requests.</li></ul><h3>🔎 2. Cross-Site Scripting (XSS)</h3><p><strong>Problem:</strong> User input is rendered as HTML/JS, allowing attackers to inject scripts.</p><p><strong>In Blade:</strong></p><pre>// ❌ Vulnerable: outputs raw HTML<br>{!! $userInput !!}<br><br>// ✅ Safe: escapes output<br>{{ $userInput }}</pre><p><strong>In Inertia/React:</strong></p><pre>// ❌ Vulnerable: using dangerouslySetInnerHTML<br>&lt;div dangerouslySetInnerHTML={{ __html: userInput }} /&gt;<br><br>// ✅ Safe: render as plain text, or sanitize first<br>&lt;div&gt;{userInput}&lt;/div&gt;<br><br>// or use DOMPurify if you must render HTML<br>import DOMPurify from &#39;dompurify&#39;;<br><br>&lt;div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userInput) }} /&gt;</pre><p><strong>Best Practices:</strong></p><ul><li>Never trust user input in HTML.</li><li>Always escape output in Blade ({{ }}) and sanitize in React if rendering HTML.</li><li>Use libraries like DOMPurify for sanitization.</li></ul><h3>🌐 3. CORS Misconfiguration</h3><p><strong>Problem:</strong> Allowing all origins (*) can expose your API to cross-origin attacks.</p><p><strong>Example (config/cors.php):</strong></p><pre>// ❌ Dangerous<br>&#39;allowed_origins&#39; =&gt; [&#39;*&#39;],<br><br>// ✅ Only allow trusted domains<br>&#39;allowed_origins&#39; =&gt; [&#39;https://yourdomain.com&#39;, &#39;https://admin.yourdomain.com&#39;],</pre><p><strong>Best Practices:</strong></p><ul><li>Never use * for APIs that require authentication.</li><li>Restrict CORS to trusted origins only.</li></ul><h3>🕓 4. Session Misconfiguration</h3><p><strong>Problem:</strong> Insecure session cookies can be stolen or manipulated.</p><p><strong>Example (config/session.php):</strong></p><pre>// ✅ Secure session settings<br>&#39;cookie_secure&#39; =&gt; env(&#39;SESSION_SECURE_COOKIE&#39;, true),<br>&#39;http_only&#39; =&gt; true,<br>&#39;same_site&#39; =&gt; &#39;lax&#39;, // or &#39;strict&#39; for extra security</pre><p><strong>Best Practices:</strong></p><ul><li>Always use HTTPS in production.</li><li>Set cookies as secure, http_only, and same_site.</li><li>Rotate session IDs after login.</li></ul><h3>🗂️ 5. Open Redirects</h3><p><strong>Problem:</strong> Redirecting to URLs from user input can allow phishing attacks.</p><pre>// ❌ Vulnerable<br>return redirect($request-&gt;input(&#39;next&#39;));<br><br>// ✅ Only allow internal URLs<br>$next = $request-&gt;input(&#39;next&#39;);<br><br>if ($next &amp;&amp; Str::startsWith($next, &#39;/&#39;)) {<br>    return redirect($next);<br>}<br><br>return redirect(&#39;/dashboard&#39;);</pre><p><strong>Best Practices:</strong></p><ul><li>Never redirect to arbitrary URLs from user input.</li><li>Always validate or sanitize redirect targets.</li></ul><h3>🗄️ 6. Unsafe File Uploads</h3><p><strong>Problem:</strong> Users can upload dangerous files (e.g., PHP scripts, malware).</p><pre>// ✅ Validate file type and size<br>$request-&gt;validate([<br>    &#39;avatar&#39; =&gt; &#39;required|image|mimes:jpeg,png,jpg,gif|max:2048&#39;,<br>]);<br><br>// ✅ Store outside public directory if possible<br>$path = $request-&gt;file(&#39;avatar&#39;)-&gt;store(&#39;avatars&#39;, &#39;private&#39;);</pre><p><strong>Best Practices:</strong></p><ul><li>Always validate file type, size, and content.</li><li>Store uploads outside the public directory if possible.</li><li>Never execute or serve uploaded files as code.</li></ul><h3>🛑 7. .env Exposure</h3><p><strong>Problem:</strong> If your web root is misconfigured, your .env file may be accessible from the web, leaking secrets.</p><p><strong>Best Practices:</strong></p><ul><li>Always set your web server root to the public/ directory.</li><li>Never commit .env files to version control.</li><li>Use environment variables for secrets in production.</li></ul><p><em>Follow me on </em><a href="https://www.linkedin.com/in/dominik-jasi%C5%84ski/"><em>LinkedIn</em></a><em> for more Laravel and DevOps content!</em></p><p><em>Would you like to learn more about security? Leave a comment below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a10f823621f0" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/secure-your-laravel-app-owasp-top-10-beyond-a10f823621f0">Secure your Laravel App: OWASP Top 10 + Beyond</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Production-Ready CI/CD with Docker on GitLab — Practical Guide]]></title>
            <link>https://levelup.gitconnected.com/production-ready-ci-cd-with-docker-on-gitlab-practical-guide-316283dccc98?source=rss-be410870b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/316283dccc98</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dominik]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 06:37:25 GMT</pubDate>
            <atom:updated>2025-07-25T14:03:42.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*FXnXOO_IfDB-wz5VXl8RPQ.png" /></figure><h3>🚀 Production-Ready CI/CD with Docker on GitLab — Practical Guide</h3><p>This guide shows how to build a professional CI/CD pipeline on GitLab for a Laravel (or any) application using Docker, buildx, automated testing, image building, and secure production deployment.</p><h3>📋 Table of Contents</h3><ul><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#-production-ready-cicd-with-docker-on-gitlab--practical-guide">🚀 Production-Ready CI/CD with Docker on GitLab — Practical Guide</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#-table-of-contents">📋 Table of Contents</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#1-introduction">1. Introduction</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#2-pipeline-structure">2. Pipeline Structure</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#full-example-gitlab-ciyml">Full Example: .gitlab-ci.yml</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#3-testing-php-and-node">3. Testing: PHP and Node</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#php-tests">PHP Tests</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#node-tests">Node Tests</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#4-building-docker-images">4. Building Docker Images</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#5-automated-production-deployment">5. Automated Production Deployment</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#6-production-checklist--best-practices">6. Production Checklist &amp; Best Practices</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#7-common-issues--debugging">7. Common Issues &amp; Debugging</a></li><li><a href="https://dominik-dev.pl/en/blog/production-ready-cicd-with-docker-on-gitlab-practical-guide#8-conclusion">8. Conclusion</a></li></ul><h3>1. Introduction</h3><p>GitLab CI/CD enables full automation of testing, building, and deploying your application. Combined with Docker, you get reproducible builds, fast tests, and secure deployments. Below is a practical description of a pipeline that works in production.</p><h3>2. Pipeline Structure</h3><h3>Full Example: .gitlab-ci.yml</h3><p>Below is a complete, ready-to-copy example of a production-ready .gitlab-ci.yml file for a Laravel project with Docker:</p><pre>image: docker:latest<br><br>stages:<br>  - test<br>  - build<br>  - deploy<br>    <br>variables:<br>  DOCKER_BUILDKIT: 1<br>  DOCKER_HOST: tcp://docker:2375/<br>  DOCKER_TLS_CERTDIR: &quot;&quot;<br>  IMAGE_NAMESPACE: dommmin/laravel-production<br>  REGISTRY: registry.gitlab.com<br>services:<br>  - docker:dind<br>before_script:<br>  - docker info<br>  - echo &quot;$CI_REGISTRY_PASSWORD&quot; | docker login -u &quot;$CI_REGISTRY_USER&quot; --password-stdin &quot;$CI_REGISTRY&quot;<br>test_php:<br>  stage: test<br>  image: dommin/php-8.4-fpm:latest<br>  needs: [test_node]<br>  before_script:<br>    - git config --global --add safe.directory $(pwd)<br>    - composer install --no-progress --no-interaction --prefer-dist --optimize-autoloader<br>  script:<br>    - cp .env.testing .env<br>    - php artisan key:generate<br>    - php artisan ziggy:generate<br>    - composer larastan<br>    - composer pint<br>    - php artisan test --env=testing<br>  variables:<br>    DB_CONNECTION: sqlite<br>    DB_DATABASE: &quot;:memory:&quot;<br>    SESSION_DRIVER: array<br>  artifacts:<br>    paths:<br>      - storage/logs/<br>    expire_in: 1 week<br>  only:<br>    - main<br>    - merge_requests<br>test_node:<br>  stage: test<br>  image: dommin/php-8.4-fpm:latest<br>  before_script:<br>    - git config --global --add safe.directory $(pwd)<br>    - npm ci<br>    - npm run build<br>  script:<br>    - npm run format<br>    - npm run types<br>    - npm run lint<br>  artifacts:<br>    paths:<br>      - node_modules/<br>      - public/build/<br>    expire_in: 1 hour<br>  only:<br>    - main<br>    - merge_requests<br>build_node:<br>  stage: build<br>  image: docker:24.0.5<br>  needs: [test_node]<br>  script:<br>    - docker buildx create --use<br>    - mkdir -p docker/node docker/php<br>    - cat &quot;$ENV_FILE&quot; &gt; docker/node/.env<br>    - cat &quot;$ENV_FILE&quot; &gt; docker/php/.env<br>    - |<br>      docker buildx build \<br>        --platform linux/amd64 \<br>        --file docker/node/Dockerfile \<br>        --tag $REGISTRY/$IMAGE_NAMESPACE/node:latest \<br>        --push \<br>        .<br>  only:<br>    - main<br>build_php:<br>  stage: build<br>  image: docker:24.0.5<br>  needs: [test_php, build_node]<br>  script:<br>    - docker buildx create --use<br>    - |<br>      docker buildx build \<br>        --platform linux/amd64 \<br>        --file docker/php/Dockerfile \<br>        --tag $REGISTRY/$IMAGE_NAMESPACE/php:latest \<br>        --push \<br>        --build-context node=docker-image://$REGISTRY/$IMAGE_NAMESPACE/node:latest \<br>        .<br>  only:<br>    - main<br>build_nginx:<br>  stage: build<br>  image: docker:24.0.5<br>  needs: [test_node, build_node]<br>  script:<br>    - docker buildx create --use<br>    - |<br>      docker buildx build \<br>        --platform linux/amd64 \<br>        --file docker/nginx/Dockerfile \<br>        --tag $REGISTRY/$IMAGE_NAMESPACE/nginx:latest \<br>        --push \<br>        --build-context node=docker-image://$REGISTRY/$IMAGE_NAMESPACE/node:latest \<br>        --build-arg HTPASSWD_USER=$HTPASSWD_USER \<br>        --build-arg HTPASSWD_PASS=$HTPASSWD_PASS \<br>        .<br>  only:<br>    - main<br>deploy_production:<br>  stage: deploy<br>  image: alpine:3.19<br>  needs: [build_node, build_php, build_nginx]<br>  before_script:<br>    - apk add --no-cache openssh-client<br>    - mkdir -p ~/.ssh<br>    - echo &quot;$SSH_KEY&quot; | tr -d &#39;\r&#39; &gt; ~/.ssh/id_rsa<br>    - chmod 600 ~/.ssh/id_rsa<br>    - ssh-keyscan -p $SSH_PORT $SSH_HOST &gt;&gt; ~/.ssh/known_hosts<br>  script:<br>    - cat &quot;$ENV_FILE&quot; &gt; .env<br>    - echo &gt;&gt; .env<br>    - |<br>      echo &quot;REGISTRY=$REGISTRY&quot; &gt;&gt; .env<br>      echo &quot;IMAGE_NAMESPACE=$IMAGE_NAMESPACE&quot; &gt;&gt; .env<br>      echo &quot;NODE_IMAGE_NAME=$IMAGE_NAMESPACE/node&quot; &gt;&gt; .env<br>      echo &quot;PHP_IMAGE_NAME=$IMAGE_NAMESPACE/php&quot; &gt;&gt; .env<br>      echo &quot;NGINX_IMAGE_NAME=$IMAGE_NAMESPACE/nginx&quot; &gt;&gt; .env<br>      echo &quot;TAG=latest&quot; &gt;&gt; .env<br>      echo &quot;CI_REGISTRY_USER=$CI_REGISTRY_USER&quot; &gt;&gt; .env<br>      echo &quot;CI_REGISTRY_PASSWORD=$CI_REGISTRY_PASSWORD&quot; &gt;&gt; .env<br>    - scp -P $SSH_PORT docker-compose.production.yml $SSH_USER@$SSH_HOST:~/laravel/docker-compose.yml<br>    - scp -P $SSH_PORT .env deploy.sh $SSH_USER@$SSH_HOST:~/laravel/<br>    - ssh -p $SSH_PORT $SSH_USER@$SSH_HOST &quot;cd ~/laravel &amp;&amp; chmod +x deploy.sh &amp;&amp; ./deploy.sh&quot;<br>  only:<br>    - main</pre><h3>3. Testing: PHP and Node</h3><h3>PHP Tests</h3><pre>test_php:<br>  stage: test<br>  image: dommin/php-8.4-fpm:latest<br>  needs: [test_node]<br>  before_script:<br>    - composer install --no-progress --no-interaction --prefer-dist --optimize-autoloader<br>  script:<br>    - cp .env.testing .env<br>    - php artisan key:generate<br>    - php artisan ziggy:generate<br>    - composer larastan<br>    - composer pint<br>    - php artisan test --env=testing<br>  variables:<br>    DB_CONNECTION: sqlite<br>    DB_DATABASE: &quot;:memory:&quot;<br>    SESSION_DRIVER: array</pre><ul><li>Tests run on a fresh Docker image.</li><li>SQLite in-memory database is used for speed.</li><li>Additionally: static analysis (larastan), formatting (pint).</li></ul><h3>Node Tests</h3><pre>test_node:<br>  stage: test<br>  image: dommin/php-8.4-fpm:latest<br>  before_script:<br>    - npm ci<br>    - npm run build<br>  script:<br>    - npm run format<br>    - npm run types<br>    - npm run lint</pre><ul><li>Checks formatting, types, and lints JS/TS code.</li><li>Builds the frontend before further steps.</li></ul><h3>4. Building Docker Images</h3><p>Each component (Node, PHP, Nginx) is built separately using docker buildx (supports multi-arch, cache, contexts):</p><pre>build_node:<br>  stage: build<br>  image: docker:24.0.5<br>  needs: [test_node]<br>  script:<br>    - docker buildx create --use<br>    - docker buildx build \<br>        --platform linux/amd64 \<br>        --file docker/node/Dockerfile \<br>        --tag $REGISTRY/$IMAGE_NAMESPACE/node:latest \<br>        --push \<br>        .</pre><ul><li>Buildx allows building images for different architectures (e.g., ARM, AMD64).</li><li>Images are pushed to a private registry (e.g., GitLab Registry).</li></ul><p>PHP and Nginx images are built analogously, passing build context (e.g., Node artifacts to PHP).</p><h3>5. Automated Production Deployment</h3><p>Deployment is done via SSH and a simple bash script:</p><pre>deploy_production:<br>  stage: deploy<br>  image: alpine:3.19<br>  needs: [build_node, build_php, build_nginx]<br>  before_script:<br>    - apk add --no-cache openssh-client<br>    - echo &quot;$SSH_KEY&quot; &gt; ~/.ssh/id_rsa<br>    - chmod 600 ~/.ssh/id_rsa<br>    - ssh-keyscan -p $SSH_PORT $SSH_HOST &gt;&gt; ~/.ssh/known_hosts<br>  script:<br>    - scp -P $SSH_PORT docker-compose.production.yml $SSH_USER@$SSH_HOST:~/laravel/docker-compose.yml<br>    - scp -P $SSH_PORT .env deploy.sh $SSH_USER@$SSH_HOST:~/laravel/<br>    - ssh -p $SSH_PORT $SSH_USER@$SSH_HOST &quot;cd ~/laravel &amp;&amp; chmod +x deploy.sh &amp;&amp; ./deploy.sh&quot;</pre><ul><li>SSH key is passed as a CI/CD variable.</li><li>Config files and the deployment script are copied to the server.</li><li>Deployment is triggered automatically.</li></ul><h3>6. Production Checklist &amp; Best Practices</h3><ul><li>ENV_FILE variable — ensure the production environment is passed correctly.</li><li>SSH keys — store them securely in GitLab CI/CD Variables.</li><li>Image registry — images are pushed to a private registry (e.g., GitLab Registry).</li><li>Tests must pass — build and deploy depend on tests.</li><li>Docker buildx — use for better performance and multi-arch support.</li><li>Artifacts — pass only necessary files (e.g., frontend build).</li><li>Automatic cache clearing — e.g., php artisan config:clear after deployment.</li><li>Logs — monitor pipeline and server logs after deployment.</li></ul><h3>7. Common Issues &amp; Debugging</h3><ul><li>Docker connection error: check if docker:dind is running and DOCKER_HOST is set.</li><li>SSH permission denied: make sure the key has correct permissions and is passed properly.</li><li>Outdated images: check if buildx is not using cache (add --no-cache if needed).</li><li>Test failures: pipeline will stop at the test stage — check logs in GitLab.</li><li>Network issues: ensure the production server accepts SSH connections from the runner.</li></ul><h3>8. Conclusion</h3><p>With such a pipeline, you have a fully automated, repeatable, and secure deployment process with tests, Docker build, and automatic deploy. This is the foundation of modern DevOps in any company!</p><p><em>For more Laravel &amp; DevOps tips: </em><a href="https://www.linkedin.com/in/dominik-jasi%C5%84ski/"><em>Dominik Jasiński on LinkedIn</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=316283dccc98" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/production-ready-ci-cd-with-docker-on-gitlab-practical-guide-316283dccc98">🚀 Production-Ready CI/CD with Docker on GitLab — Practical Guide</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Linux Administration & DevOps Guide]]></title>
            <link>https://medium.com/@Dommin/linux-administration-devops-guide-32cf3090b5f2?source=rss-be410870b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/32cf3090b5f2</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Dominik]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 10:18:05 GMT</pubDate>
            <atom:updated>2025-06-06T10:18:05.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2Aqg5u-lqFSde3ENuJpcw.jpeg" /></figure><h3>Introduction</h3><p>Linux administration and DevOps practices are essential skills for modern developers and system administrators. This guide is specifically designed for junior developers and those new to Linux administration. We’ll cover everything from setting up a local development environment to managing production servers, with a focus on security, performance, and best practices. Each section includes detailed explanations and practical examples to help you understand the concepts better.</p><h3>What is DevOps?</h3><p>DevOps is a set of practices that combines software development (Dev) and IT operations (Ops). It aims to shorten the development lifecycle and provide continuous delivery with high software quality. As a junior developer, understanding DevOps practices will help you:</p><ul><li>Deploy applications more efficiently</li><li>Collaborate better with your team</li><li>Understand the full application lifecycle</li><li>Write more production-ready code</li></ul><h3>Why Linux?</h3><p>Linux is the most popular operating system for servers and development environments because:</p><ul><li>It’s free and open-source</li><li>Highly secure and stable</li><li>Excellent for development and deployment</li><li>Most cloud services run on Linux</li><li>Most development tools are Linux-first</li></ul><h3>Local Development Environment</h3><h3>Setting Up Your Workstation</h3><p>Before we start, let’s understand what each tool does:</p><ul><li><strong>git</strong>: Version control system for tracking code changes</li><li><strong>curl &amp; wget</strong>: Tools for downloading files from the internet</li><li><strong>vim</strong>: Text editor for editing files in the terminal</li><li><strong>htop</strong>: Interactive process viewer (better than the basic ‘top’ command)</li><li><strong>tmux</strong>: Terminal multiplexer (allows you to run multiple terminal sessions)</li><li><strong>build-essential</strong>: Contains basic tools for building software</li><li><strong>software-properties-common</strong>: Helps manage software repositories</li></ul><pre># Update system<br># This command updates the list of available packages and their versions<br>sudo apt update &amp;&amp; sudo apt upgrade<br><br># Install essential development tools<br># The -y flag automatically answers &quot;yes&quot; to prompts<br>sudo apt install -y \<br>    git \<br>    curl \<br>    wget \<br>    vim \<br>    htop \<br>    tmux \<br>    build-essential \<br>    software-properties-common<br><br># Install Docker &amp;&amp; Docker Compose<br># Docker helps you run applications in isolated containers<br># Docker Compose helps you manage multiple containers<br># This makes it easier to develop and deploy applications<br>curl -fsSL https://get.docker.com | sudo sh</pre><h3>Development Tools</h3><p>Let’s understand what each development tool does:</p><ul><li><strong>Node.js</strong>: JavaScript runtime for building server-side applications</li><li><strong>npm</strong>: Node.js package manager for installing JavaScript libraries</li><li><strong>PHP</strong>: Server-side scripting language</li><li><strong>Composer</strong>: PHP package manager for managing PHP dependencies</li></ul><pre># Install Node.js and npm<br># LTS means &quot;Long Term Support&quot; - more stable version<br>curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -<br>sudo apt install -y nodejs<br><br># Install PHP and common extensions<br># Each extension adds specific functionality to PHP:<br># - php-fpm: FastCGI Process Manager for PHP<br># - php-mysql: MySQL database support<br># - php-gd: Image processing<br># - php-mbstring: Multibyte string handling<br># - php-xml: XML processing<br>sudo apt install -y \<br>    php \<br>    php-cli \<br>    php-fpm \<br>    php-json \<br>    php-common \<br>    php-mysql \<br>    php-zip \<br>    php-gd \<br>    php-mbstring \<br>    php-curl \<br>    php-xml \<br>    php-bcmath<br><br># Install Composer<br># Composer is like npm but for PHP<br>curl -sS https://getcomposer.org/installer | php<br>sudo mv composer.phar /usr/local/bin/composer</pre><h3>Server Administration</h3><h3>Initial Server Setup</h3><p>When you first get access to a server, these are the essential steps to secure it:</p><ol><li><strong>Update the system</strong>: Always start with an updated system</li><li><strong>Create a deploy user</strong>: Never use root for daily operations</li><li><strong>Set up SSH keys</strong>: More secure than passwords</li><li><strong>Configure SSH</strong>: Disable password login and root access</li></ol><pre># Update system<br>sudo apt update &amp;&amp; sudo apt upgrade<br><br># Create new user<br># This creates a user named &#39;deploy&#39; with a home directory<br>sudo adduser deploy<br># Add the user to the sudo group (allows running commands as root)<br>sudo usermod -aG sudo deploy<br><br># Set up SSH key authentication<br># SSH keys are more secure than passwords<br># They use public-key cryptography<br>mkdir -p ~/.ssh<br>chmod 700 ~/.ssh  # Restrict permissions to owner only<br>touch ~/.ssh/authorized_keys<br>chmod 600 ~/.ssh/authorized_keys  # Restrict permissions to owner only<br><br># Configure SSH<br>sudo nano /etc/ssh/sshd_config<br># These settings make your server more secure:<br># PermitRootLogin no        # Prevents root login<br># PasswordAuthentication no # Disables password login<br># PubkeyAuthentication yes # Enables key-based authentication</pre><h3>Server Security</h3><p>Security is crucial for any server. Here’s what each security measure does:</p><ul><li><strong>UFW (Uncomplicated Firewall)</strong>: A user-friendly interface for managing firewall rules</li><li><strong>fail2ban</strong>: Protects against brute-force attacks by banning IPs that fail to authenticate</li></ul><pre># Install and configure firewall<br>sudo apt install -y ufw<br><br># Default policies<br>sudo ufw default deny incoming  # Block all incoming connections by default<br>sudo ufw default allow outgoing # Allow all outgoing connections<br><br># Allow specific services<br>sudo ufw allow ssh    # Port 22<br>sudo ufw allow http   # Port 80<br>sudo ufw allow https  # Port 443<br>sudo ufw enable       # Start the firewall<br><br># Install fail2ban<br># fail2ban monitors log files and bans IPs that show malicious behavior<br>sudo apt install -y fail2ban<br>sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local  # Create custom config<br>sudo systemctl enable fail2ban  # Start on boot<br>sudo systemctl start fail2ban   # Start now</pre><h3>Remote Access &amp; Security</h3><h3>SSH Configuration</h3><p>SSH (Secure Shell) is the primary way to access remote servers. Here’s how to set it up securely:</p><ol><li><strong>Generate an SSH key</strong>: Creates a pair of keys (public and private)</li><li><strong>Copy the public key</strong>: Adds your key to the server’s authorized keys</li><li><strong>Configure SSH client</strong>: Makes connecting easier</li></ol><pre># Generate SSH key<br># -t ed25519: Use the Ed25519 algorithm (more secure than RSA)<br># -C: Add a comment (usually your email)<br>ssh-keygen -t ed25519 -C &quot;your_email@example.com&quot;<br><br># Copy key to server<br># This adds your public key to the server&#39;s authorized_keys file<br>ssh-copy-id user@server_ip<br><br># SSH config file (~/.ssh/config)<br># This file makes it easier to connect to your servers<br># Instead of typing the full command, you can just type &#39;ssh myserver&#39;<br>Host myserver<br>    HostName server_ip        # The server&#39;s IP address<br>    User username             # Your username on the server<br>    IdentityFile ~/.ssh/id_ed25519  # Your private key<br>    Port 22                   # SSH port (default is 22)</pre><h3>Secure File Transfer</h3><p>There are two main ways to transfer files securely:</p><ol><li><strong>SCP (Secure Copy)</strong>: Simple file transfer</li><li><strong>RSYNC</strong>: More powerful, with features like:</li></ol><ul><li>Resume interrupted transfers</li><li>Only copy changed files</li><li>Compression</li><li>Progress display</li></ul><pre># SCP (Secure Copy)<br># Basic file transfer<br>scp file.txt user@server:/path/to/destination<br><br># Transfer a directory<br>scp -r directory/ user@server:/path/to/destination<br><br># RSYNC (with compression and progress)<br># -a: archive mode (preserves permissions, etc.)<br># -v: verbose<br># -z: compress during transfer<br># --progress: show progress<br>rsync -avz --progress source/ user@server:/path/to/destination<br><br># Mirror directories (delete files that don&#39;t exist in source)<br>rsync -avz --delete source/ user@server:/path/to/destination</pre><h3>Monitoring &amp; Debugging</h3><h3>System Monitoring</h3><p>Understanding your system’s health is crucial. Here are the key tools:</p><ol><li><strong>Process Monitoring</strong>:</li></ol><ul><li>top: Basic process viewer</li><li>htop: Enhanced process viewer with better interface</li><li>ps: List processes</li><li>pgrep: Find processes by name</li></ul><p><strong>2. Resource Usage</strong>:</p><ul><li>df: Disk space</li><li>free: Memory usage</li><li>vmstat: Virtual memory statistics</li><li>iostat: I/O statistics</li><li>netstat: Network connections</li></ul><p><strong>3. Log Monitoring</strong>:</p><ul><li>System logs: General system events</li><li>Journal logs: Systemd service logs</li><li>Kernel logs: Hardware and driver messages</li></ul><pre># Process monitoring<br>top        # Basic process viewer<br>htop       # More user-friendly process viewer<br>ps aux | grep process_name  # Find specific process<br>pgrep process_name         # Get process ID by name<br><br># Resource usage<br>df -h      # Show disk space in human-readable format<br>free -h    # Show memory usage in human-readable format<br>vmstat 1   # Show virtual memory stats every 1 second<br>iostat     # Show I/O statistics<br>netstat -tulpn  # Show all listening ports and connections<br><br># Log monitoring<br>tail -f /var/log/syslog    # Follow system log in real-time<br>journalctl -f              # Follow systemd logs in real-time<br>dmesg                      # Show kernel messages</pre><h3>Performance Analysis</h3><p>When your system is slow, these tools help identify the cause:</p><ol><li><strong>CPU Profiling</strong>:</li></ol><ul><li>perf: Performance analysis tools</li><li>Shows which functions use the most CPU</li></ul><p><strong>2. Memory Analysis</strong>:</p><ul><li>free: Basic memory usage</li><li>vmstat: Detailed memory statistics</li><li>/proc/meminfo: Raw memory information</li></ul><ol><li><strong>Disk I/O</strong>:</li></ol><ul><li>iostat: I/O statistics</li><li>iotop: Real-time I/O monitoring</li></ul><pre># CPU profiling<br>perf top              # Show CPU usage by function<br>perf record -g -p PID # Record CPU usage for a process<br>perf report           # Analyze the recording<br><br># Memory analysis<br>free -h               # Show memory usage<br>vmstat 1             # Show memory stats every second<br>cat /proc/meminfo    # Show detailed memory information<br><br># Disk I/O<br>iostat -x 1          # Show I/O stats every second<br>iotop                # Show I/O usage by process</pre><h3>Performance Optimization</h3><h3>System Tuning</h3><p>System tuning involves adjusting kernel parameters for better performance:</p><ol><li><strong>File Descriptors</strong>: Limit of open files</li><li><strong>TCP Settings</strong>: Network connection handling</li><li><strong>Memory Management</strong>: How the system uses memory</li></ol><pre># Kernel parameters (/etc/sysctl.conf)<br># Increase file descriptors<br># This is important for web servers handling many connections<br>fs.file-max = 65535<br><br># TCP optimization<br># These settings help with network performance<br>net.ipv4.tcp_syncookies = 1        # Protect against SYN flood attacks<br>net.ipv4.tcp_max_syn_backlog = 65535  # Increase connection queue<br>net.ipv4.tcp_fin_timeout = 30      # Reduce time to close connections<br><br># Apply changes<br>sudo sysctl -p  # Reload kernel parameters</pre><h3>Backup</h3><h3>Automated Backups</h3><p>Regular backups are crucial.</p><pre># Database backup script<br>#!/bin/bash<br># Configuration<br>BACKUP_DIR=&quot;/backup/mysql&quot;<br>DATE=$(date +%Y%m%d_%H%M%S)<br>DB_USER=&quot;user&quot;<br>DB_PASS=&quot;password&quot;<br>DB_NAME=&quot;database&quot;<br><br># Create backup<br># mysqldump creates a SQL file of your database<br># gzip compresses it to save space<br>mysqldump -u $DB_USER -p$DB_PASS $DB_NAME | gzip &gt; $BACKUP_DIR/$DB_NAME-$DATE.sql.gz<br><br># Remove old backups<br># Keep only the last 7 days of backups<br>find $BACKUP_DIR -name &quot;*.sql.gz&quot; -mtime +7 -delete<br><br># Backup files<br># tar creates an archive<br># -c: create<br># -z: compress with gzip<br># -f: specify filename<br>tar -czf /backup/files/website-$DATE.tar.gz /var/www/website</pre><h3>Best Practices</h3><h3>Security</h3><ol><li><strong>Regular Updates</strong>: Keep your system secure</li><li><strong>Strong Passwords</strong>: Use complex passwords</li><li><strong>SSH Keys</strong>: More secure than passwords</li><li><strong>Firewall</strong>: Control network access</li><li><strong>Security Audits</strong>: Regular security checks</li><li><strong>File Permissions</strong>: Restrict access to files</li><li><strong>SSL/TLS</strong>: Encrypt network traffic</li><li><strong>Backup Verification</strong>: Test your backups</li></ol><h3>Performance</h3><ol><li><strong>Regular Monitoring</strong>: Watch system health</li><li><strong>Resource Optimization</strong>: Use resources efficiently</li><li><strong>Cache Implementation</strong>: Speed up access</li><li><strong>Load Balancing</strong>: Distribute traffic</li><li><strong>CDN Usage</strong>: Serve content faster</li><li><strong>Database Optimization</strong>: Speed up queries</li><li><strong>Log Rotation</strong>: Manage log files</li><li><strong>Regular Maintenance</strong>: Keep system clean</li></ol><h3>Maintenance</h3><ol><li><strong>Regular Backups</strong>: Protect your data</li><li><strong>Update Schedules</strong>: Plan updates</li><li><strong>Monitoring Alerts</strong>: Get notified of issues</li><li><strong>Documentation</strong>: Keep track of changes</li><li><strong>Change Management</strong>: Control changes</li><li><strong>Testing Procedures</strong>: Test before deploying</li><li><strong>Rollback Plans</strong>: Prepare for failures</li><li><strong>Security Patches</strong>: Apply security updates</li></ol><p>🔗 Follow me on <a href="https://www.linkedin.com/in/dominik-jasi%C5%84ski/">LinkedIn</a> for more DevOps tips and updates!</p><p>💡 Found this guide helpful? Share it with your team and follow for more DevOps content!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32cf3090b5f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Implementing Social Login in Laravel: A Complete Guide to Google and Facebook Authentication]]></title>
            <link>https://levelup.gitconnected.com/implementing-social-login-in-laravel-a-complete-guide-to-google-and-facebook-authentication-af6196c73202?source=rss-be410870b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/af6196c73202</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Dominik]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 10:44:21 GMT</pubDate>
            <atom:updated>2025-06-04T14:10:52.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuRADHGisCf-l1yuLBhxDw.png" /></figure><p>In this comprehensive guide, we’ll implement social login functionality in a Laravel application using Laravel Socialite. We’ll cover both Google and Facebook authentication, including the complete setup process from creating OAuth credentials to implementing the frontend and backend code.</p><h3>Introduction</h3><p>Social login provides a seamless authentication experience for your users, allowing them to sign in using their existing Google or Facebook accounts. This guide will walk you through the complete implementation process, from setting up OAuth credentials to handling user creation and authentication.</p><h3>Setting Up OAuth Credentials</h3><h3>Google OAuth Setup</h3><h4>1. Configure the Consent Screen</h4><ol><li>Go to <a href="https://console.cloud.google.com/">Google Cloud Console</a></li><li>Create a new project or select an existing one</li><li>Navigate to “APIs &amp; Services” &gt; “OAuth consent screen”</li><li>Choose the user type:</li></ol><ul><li><strong>For development/testing: Select “External”</strong></li><li>This allows you to test it with any Google account</li><li>Your app will be in testing mode</li><li>You can add up to 100 test users</li><li>No verification required for testing</li><li><strong>For production/internal apps: Select “Internal”</strong></li><li>Only available to users within your organization</li><li>Requires Google Workspace</li><li>No verification needed</li><li>Limited to your organization’s users</li></ul><p>5. Fill in the required app information:</p><pre>App name: Your App Name <br>User support email: your-email@example.com <br>Developer contact information: your-email@example.com</pre><h4>2. Create OAuth Credentials</h4><ol><li>Go to “APIs &amp; Services” &gt; “Credentials”</li><li>Click “Create Credentials” &gt; “OAuth client ID”</li><li>Choose “Web application” as the application type</li><li>Set the name for your OAuth client</li><li>Add authorized redirect URIs:</li></ol><ul><li>For development: <a href="http://localhost/auth/google/callback">http://localhost/auth/google/callback</a></li><li>For production: <a href="https://your-domain.com/auth/google/callback">https://your-domain.com/auth/google/callback</a></li></ul><p>6. Click “Create”<br>7. Save your Client ID and Client Secret</p><h3>Facebook OAuth Setup</h3><h4>1. Creating a Business Account</h4><ol><li>Go to <a href="https://business.facebook.com/">Facebook Business</a></li><li>Click “Create Account”</li><li>Fill in your business information:</li></ol><ul><li>Business Name (e.g., “Your Business name”)</li><li>Business Email (e.g., dev@your-domain.com)</li><li>Business Address</li><li>Business Phone Number</li></ul><p>4. Verify your business email<br>5. Add your business details:</p><ul><li>Industry</li><li>Business Type</li><li>Business Category</li></ul><h4>2. Creating a Developer Account</h4><ol><li>Go to <a href="https://developers.facebook.com/">Facebook Developers</a></li><li>Click “Get Started” or “Log In”</li><li>If you’re using your business account:</li></ol><ul><li>Select your business account</li><li>Choose “Developer” role</li></ul><p>4. Accept the Facebook Platform Terms<br>5. Complete the developer registration:</p><ul><li>Add your developer contact email</li><li>Add your developer website</li><li>Add your developer privacy policy URL</li></ul><h4>3. Creating a New App</h4><ol><li>In Facebook Developers Console, click “Create App”</li><li>Choose “Consumer” as the app type</li><li>Fill in the basic app information:</li></ol><pre>App Name: Your App Name App <br>Contact Email: dev@your-domain.com <br>Business Account: Select your business account</pre><p>4. Click “Create App”</p><h4>4. Configuring Facebook Login</h4><ol><li>In your app dashboard, go to “Facebook Login” &gt; “Settings”</li><li>Configure basic settings:</li></ol><ul><li>Client OAuth Login: Yes</li><li>Web OAuth Login: Yes</li><li>Enforce HTTPS: No (for development)</li></ul><p>3. Add OAuth redirect URI:</p><ul><li>For development: <a href="http://localhost/auth/facebook/callback">http://localhost/auth/facebook/callback</a></li><li>For production: <a href="https://your-domain.com/auth/facebook/callback">https://your-domain.com/auth/facebook/callback</a></li></ul><p>4. Configure App Domains:</p><ul><li>Add localhost for development</li><li>Add your production domain when ready</li></ul><p>5. Add required permissions (scopes):</p><ul><li>email (required for getting user&#39;s email)</li><li>public_profile (required for basic profile info)</li></ul><h3>Implementation Steps</h3><h3>Installing Required Packages</h3><pre>composer require laravel/socialite</pre><h3>Configuration</h3><h4>1. Update Environment Variables</h4><p>Add these to your .env file:</p><pre># Google OAuth<br>GOOGLE_CLIENT_ID=your-google-client-id<br>GOOGLE_CLIENT_SECRET=your-google-client-secret<br>GOOGLE_REDIRECT_URI=&quot;${APP_URL}/auth/google/callback&quot;<br><br># Facebook OAuth<br>FACEBOOK_CLIENT_ID=your-facebook-app-id<br>FACEBOOK_CLIENT_SECRET=your-facebook-app-secret<br>FACEBOOK_REDIRECT_URI=&quot;${APP_URL}/auth/facebook/callback&quot;</pre><h4>2. Update Services Configuration</h4><p>Edit config/services.php:</p><pre>&#39;google&#39; =&gt; [<br>    &#39;client_id&#39; =&gt; env(&#39;GOOGLE_CLIENT_ID&#39;),<br>    &#39;client_secret&#39; =&gt; env(&#39;GOOGLE_CLIENT_SECRET&#39;),<br>    &#39;redirect&#39; =&gt; env(&#39;GOOGLE_REDIRECT_URI&#39;),<br>],<br><br>&#39;facebook&#39; =&gt; [<br>    &#39;client_id&#39; =&gt; env(&#39;FACEBOOK_CLIENT_ID&#39;),<br>    &#39;client_secret&#39; =&gt; env(&#39;FACEBOOK_CLIENT_SECRET&#39;),<br>    &#39;redirect&#39; =&gt; env(&#39;FACEBOOK_REDIRECT_URI&#39;),<br>],</pre><h3>Database Migration</h3><p>Create a migration to add social login columns:</p><pre>php artisan make:migration add_social_login_columns_to_users_table --table=users</pre><p>Edit the migration file:</p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br>return new class extends Migration<br>{<br>    public function up(): void<br>    {<br>        Schema::table(&#39;users&#39;, function (Blueprint $table) {<br>            $table-&gt;string(&#39;google_id&#39;)-&gt;nullable()-&gt;after(&#39;id&#39;);<br>            $table-&gt;string(&#39;facebook_id&#39;)-&gt;nullable()-&gt;after(&#39;google_id&#39;);<br>            $table-&gt;text(&#39;google_token&#39;)-&gt;nullable();<br>            $table-&gt;text(&#39;facebook_token&#39;)-&gt;nullable();<br>            $table-&gt;text(&#39;google_refresh_token&#39;)-&gt;nullable();<br>            $table-&gt;text(&#39;facebook_refresh_token&#39;)-&gt;nullable();<br>        });<br>    }<br>    public function down(): void<br>    {<br>        Schema::table(&#39;users&#39;, function (Blueprint $table) {<br>            $table-&gt;dropColumn([<br>                &#39;google_id&#39;,<br>                &#39;facebook_id&#39;,<br>                &#39;google_token&#39;,<br>                &#39;facebook_token&#39;,<br>                &#39;google_refresh_token&#39;,<br>                &#39;facebook_refresh_token&#39;,<br>            ]);<br>        });<br>    }<br>};</pre><p>Run the migration:</p><pre>php artisan migrate</pre><h3>Creating the Social Login Controller</h3><pre>php artisan make:controller Auth/SocialLoginController</pre><p>Implement the controller:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers\Auth;<br><br>use App\Http\Controllers\Controller;<br>use App\Models\User;<br>use Illuminate\Support\Facades\Auth;<br>use Illuminate\Support\Facades\Log;<br>use Laravel\Socialite\Facades\Socialite;<br>use Laravel\Socialite\Two\User as SocialiteUser;<br>use Symfony\Component\HttpFoundation\RedirectResponse;<br><br>class SocialLoginController extends Controller<br>{<br>    public function redirectToGoogle(): RedirectResponse<br>    {<br>        return Socialite::driver(&#39;google&#39;)-&gt;redirect();<br>    }<br><br>    public function handleGoogleCallback(): RedirectResponse<br>    {<br>        try {<br>            /* @var SocialiteUser $googleUser */<br>            $googleUser = Socialite::driver(&#39;google&#39;)-&gt;user();<br>            $user = User::updateOrCreate(<br>                [&#39;email&#39; =&gt; $googleUser-&gt;getEmail()],<br>                [<br>                    &#39;name&#39; =&gt; $googleUser-&gt;getName(),<br>                    &#39;email&#39; =&gt; $googleUser-&gt;getEmail(),<br>                    &#39;google_id&#39; =&gt; $googleUser-&gt;getId(),<br>                    &#39;google_token&#39; =&gt; $googleUser-&gt;token,<br>                    &#39;google_refresh_token&#39; =&gt; $googleUser-&gt;refreshToken,<br>                ]<br>            );<br>            Auth::login($user);<br>            return redirect()-&gt;intended(route(&#39;home&#39;));<br>        } catch (\Exception $e) {<br>            Log::error(&#39;Google authentication failed: &#39; . $e-&gt;getMessage());<br>            return redirect()-&gt;route(&#39;login&#39;)-&gt;with(&#39;error&#39;, &#39;Google authentication failed&#39;);<br>        }<br>    }<br><br>    public function redirectToFacebook(): RedirectResponse<br>    {<br>        return Socialite::driver(&#39;facebook&#39;)-&gt;redirect();<br>    }<br><br>    public function handleFacebookCallback(): RedirectResponse<br>    {<br>        try {<br>            /* @var SocialiteUser $facebookUser */<br>            $facebookUser = Socialite::driver(&#39;facebook&#39;)-&gt;user();<br>            $user = User::updateOrCreate(<br>                [&#39;email&#39; =&gt; $facebookUser-&gt;getEmail()],<br>                [<br>                    &#39;name&#39; =&gt; $facebookUser-&gt;getName(),<br>                    &#39;email&#39; =&gt; $facebookUser-&gt;getEmail(),<br>                    &#39;facebook_id&#39; =&gt; $facebookUser-&gt;getId(),<br>                    &#39;facebook_token&#39; =&gt; $facebookUser-&gt;token,<br>                    &#39;facebook_refresh_token&#39; =&gt; $facebookUser-&gt;refreshToken,<br>                ]<br>            );<br>            Auth::login($user);<br>            return redirect()-&gt;intended(route(&#39;home&#39;));<br>        } catch (\Exception $e) {<br>            Log::error(&#39;Facebook authentication failed: &#39; . $e-&gt;getMessage());<br>            return redirect()-&gt;route(&#39;login&#39;)-&gt;with(&#39;error&#39;, &#39;Facebook authentication failed&#39;);<br>        }<br>    }<br>}</pre><h3>Handling User Creation</h3><p>Since Laravel requires a password for user creation, we need to generate a random password for social login users. We’ll use an observer to handle this automatically.</p><h4>1. Create UserObserver</h4><pre>php artisan make:observer UserObserver --model=User</pre><h4>2. Add ObservedBy Attribute to User Model</h4><pre>&lt;?php<br><br>namespace App\Models;<br>use App\Observers\UserObserver;<br>use Illuminate\Foundation\Auth\User as Authenticatable;<br>use Illuminate\Notifications\Notifiable;<br>use Laravel\Sanctum\HasApiTokens;<br>#[ObservedBy(UserObserver::class)]<br>class User extends Authenticatable<br>{<br>    use HasApiTokens, Notifiable;<br>    // ... rest of the model<br>}</pre><h4>3. Implement UserObserver</h4><pre>&lt;?php<br><br>namespace App\Observers;<br>use App\Models\User;<br>use Illuminate\Support\Str;<br>class UserObserver<br>{<br>    public function creating(User $user): void<br>    {<br>        if (!$user-&gt;password) {<br>            $user-&gt;password = bcrypt(Str::random(24));<br>        }<br>    }<br>}</pre><h3>Adding Routes</h3><p>Add these routes to routes/auth.php:</p><pre>Route::middleware(&#39;guest&#39;)-&gt;group(function (): void {<br>    // ... existing routes ...<br><br>// Social Login Routes<br>    Route::get(&#39;auth/google&#39;, [SocialLoginController::class, &#39;redirectToGoogle&#39;])<br>        -&gt;name(&#39;auth.google&#39;);<br>    Route::get(&#39;auth/google/callback&#39;, [SocialLoginController::class, &#39;handleGoogleCallback&#39;])<br>        -&gt;name(&#39;auth.google.callback&#39;);<br>    Route::get(&#39;auth/facebook&#39;, [SocialLoginController::class, &#39;redirectToFacebook&#39;])<br>        -&gt;name(&#39;auth.facebook&#39;);<br>    Route::get(&#39;auth/facebook/callback&#39;, [SocialLoginController::class, &#39;handleFacebookCallback&#39;])<br>        -&gt;name(&#39;auth.facebook.callback&#39;);<br>});</pre><h3>Implementing the Frontend</h3><p>For a React/TypeScript frontend using Inertia.js, update your login component:</p><pre>import { Head, Link, useForm } from &#39;@inertiajs/react&#39;;<br>import { LoaderCircle } from &#39;lucide-react&#39;;<br><br>// ... other imports ...<br>export default function Login({ status, canResetPassword }: LoginProps) {<br>    // ... existing form logic ...<br>    return (<br>        &lt;AuthLayout title=&quot;Log in to your account&quot; description=&quot;Enter your email and password below to log in&quot;&gt;<br>            &lt;Head title=&quot;Log in&quot; /&gt;<br>            &lt;div className=&quot;flex flex-col gap-6&quot;&gt;<br>                &lt;div className=&quot;grid grid-cols-2 gap-4&quot;&gt;<br>                    &lt;Button<br>                        variant=&quot;outline&quot;<br>                        type=&quot;button&quot;<br>                        onClick={() =&gt; window.location.href = route(&#39;auth.google&#39;)}<br>                        className=&quot;w-full&quot;<br>                    &gt;<br>                        &lt;svg className=&quot;mr-2 h-4 w-4&quot; viewBox=&quot;0 0 24 24&quot;&gt;<br>                            {/* Google icon SVG */}<br>                        &lt;/svg&gt;<br>                        Google<br>                    &lt;/Button&gt;<br>                    &lt;Button<br>                        variant=&quot;outline&quot;<br>                        type=&quot;button&quot;<br>                        onClick={() =&gt; window.location.href = route(&#39;auth.facebook&#39;)}<br>                        className=&quot;w-full&quot;<br>                    &gt;<br>                        &lt;svg className=&quot;mr-2 h-4 w-4&quot; viewBox=&quot;0 0 24 24&quot; fill=&quot;#1877F2&quot;&gt;<br>                            {/* Facebook icon SVG */}<br>                        &lt;/svg&gt;<br>                        Facebook<br>                    &lt;/Button&gt;<br>                &lt;/div&gt;<br>                &lt;div className=&quot;relative&quot;&gt;<br>                    &lt;div className=&quot;absolute inset-0 flex items-center&quot;&gt;<br>                        &lt;span className=&quot;w-full border-t&quot; /&gt;<br>                    &lt;/div&gt;<br>                    &lt;div className=&quot;relative flex justify-center text-xs uppercase&quot;&gt;<br>                        &lt;span className=&quot;bg-background px-2 text-muted-foreground&quot;&gt;<br>                            Or continue with<br>                        &lt;/span&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>                {/* Existing login form */}<br>            &lt;/div&gt;<br>        &lt;/AuthLayout&gt;<br>    );<br>}</pre><h3>Common Issues and Solutions</h3><ol><li><strong>Invalid Redirect URI</strong></li></ol><ul><li>Ensure the redirect URI in your .env matches exactly with the one in the OAuth provider’s console</li><li>Check for trailing slashes or spaces</li><li>Verify the protocol (http/https)</li></ul><p><strong>2. Facebook HTTPS Requirement</strong></p><ul><li>Use Development Mode for local testing</li><li>Ensure HTTPS in production</li><li>Add localhost to App Domains for development</li></ul><p><strong>3. Google Consent Screen</strong></p><ul><li>For testing: Use External user type with test users</li><li>For production: Either use Internal (organization only) or complete verification for External</li></ul><p><strong>4. Token Storage</strong></p><ul><li>Store tokens securely</li><li>Consider encrypting sensitive data</li><li>Implement token refresh logic for Google</li></ul><p><strong>5. Redirect URI Mismatch</strong></p><ul><li>Ensure the redirect URI in Google Cloud Console exactly matches your application’s callback URL</li><li>For Docker with Nginx setup, use http://localhost/auth/google/callback (no port number)</li><li>Clear Laravel’s cache if you’ve changed the configuration:</li></ul><pre>php artisan config:clear <br>php artisan cache:clear <br>php artisan route:clear</pre><ul><li>If the issue persists, try recreating the OAuth credentials</li></ul><h3>Security Considerations</h3><ol><li>Always use HTTPS in production</li><li>Implement proper error handling</li><li>Validate user data from social providers</li><li>Consider implementing email verification</li><li>Store tokens securely</li><li>Implement proper session management</li><li>Use CSRF protection</li><li>Consider rate limiting</li></ol><h3>Conclusion</h3><p>Implementing social login in Laravel using Socialite provides a seamless authentication experience for your users. By following this guide, you’ve set up a secure and maintainable social authentication system that works both in development and production environments.</p><p>Remember to:</p><ul><li>Keep your OAuth credentials secure</li><li>Regularly update your dependencies</li><li>Monitor your application logs</li><li>Implement proper error handling</li><li>Test thoroughly in both development and production environments</li></ul><p><em>Follow me on </em><a href="https://www.linkedin.com/in/dominik-jasi%C5%84ski/"><em>LinkedIn</em></a><em> for more Laravel and authentication tips!</em></p><p><em>Would you like to learn more about Laravel authentication or social login implementation? Let me know in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af6196c73202" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/implementing-social-login-in-laravel-a-complete-guide-to-google-and-facebook-authentication-af6196c73202">🔐 Implementing Social Login in Laravel: A Complete Guide to Google and Facebook Authentication</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Definitive Guide to PDF Generation in Laravel: Spatie Browsershot vs DomPDF]]></title>
            <link>https://levelup.gitconnected.com/the-definitive-guide-to-pdf-generation-in-laravel-spatie-browsershot-vs-dompdf-de2b0a4947d5?source=rss-be410870b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/de2b0a4947d5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Dominik]]></dc:creator>
            <pubDate>Fri, 30 May 2025 11:24:29 GMT</pubDate>
            <atom:updated>2025-06-01T22:06:27.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSjTOUFdRkeEe9z5uCaX6Q.png" /></figure><h3>Introduction</h3><p>This article demonstrates how to implement two popular solutions for PDF generation in Laravel: <a href="https://spatie.be/docs/laravel-pdf/v1/introduction">Spatie Laravel PDF (with Browsershot)</a> and <a href="https://github.com/barryvdh/laravel-dompdf">barryvdh/laravel-dompdf</a>. Both have their strengths and limitations — below you’ll find setup instructions, usage examples, a comparison, and recommendations for when to use each.</p><h3>Installation &amp; Setup</h3><h3>1. Spatie Laravel PDF (Browsershot)</h3><ul><li>Install the package:</li></ul><pre>composer require spatie/laravel-pdf <br>npm install puppeteer <br>npx puppeteer browsers install chrome</pre><ul><li>Make sure Chromium is installed in your Docker PHP image (if using Docker):</li></ul><pre>RUN apt-get update \<br>    &amp;&amp; apt-get install -y wget gnupg2 \<br>    &amp;&amp; wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \<br>    &amp;&amp; echo &quot;deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main&quot; &gt; /etc/apt/sources.list.d/google-chrome.list \<br>    &amp;&amp; apt-get update \<br>    &amp;&amp; apt-get install -y google-chrome-stable \<br>    &amp;&amp; apt-get clean \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><h3>2. barryvdh/laravel-dompdf</h3><ul><li>Install the package:</li></ul><pre>composer require barryvdh/laravel-dompdf <br>php artisan vendor:publish --provider=&quot;Barryvdh\DomPDF\ServiceProvider&quot;</pre><ul><li>No extra system dependencies required. Styling is limited to basic CSS.</li></ul><h3>Example Routes and Controller</h3><p>In routes/web.php:</p><pre>Route::get(&#39;/pdf/spatie&#39;, [PdfDemoController::class, &#39;spatie&#39;])-&gt;name(&#39;pdf.spatie&#39;);<br>Route::get(&#39;/pdf/dompdf&#39;, [PdfDemoController::class, &#39;dompdf&#39;])-&gt;name(&#39;pdf.dompdf&#39;);</pre><p>In app/Http/Controllers/PdfDemoController.php:</p><pre>&lt;?php<br><br>declare(strict_types=1);<br><br>namespace App\Http\Controllers;<br><br>use Barryvdh\DomPDF\Facade\Pdf as DomPdf;<br>use Illuminate\Http\Request;<br>use Illuminate\Http\Response;<br>use Spatie\Browsershot\Browsershot;<br>use Spatie\LaravelPdf\Facades\Pdf;<br><br>class PdfDemoController extends Controller<br>{<br>    public function spatie(Request $request)<br>    {<br>        $data = [<br>            &#39;user&#39; =&gt; [<br>                &#39;name&#39; =&gt; &#39;John Doe&#39;,<br>                &#39;email&#39; =&gt; &#39;john@example.com&#39;,<br>            ],<br>            &#39;items&#39; =&gt; [<br>                [&#39;name&#39; =&gt; &#39;Super Product&#39;, &#39;qty&#39; =&gt; 2, &#39;price&#39; =&gt; 199.99],<br>                [&#39;name&#39; =&gt; &#39;Mega Service&#39;, &#39;qty&#39; =&gt; 1, &#39;price&#39; =&gt; 499.00],<br>            ],<br>            &#39;total&#39; =&gt; 199.99 * 2 + 499.00,<br>        ];<br>        return Pdf::view(&#39;pdfs.spatie-invoice&#39;, $data)<br>            -&gt;withBrowsershot(function (Browsershot $browsershot): void {<br>                $browsershot-&gt;noSandbox()-&gt;format(&#39;A4&#39;);<br>            })<br>            -&gt;download(&#39;spatie-invoice.pdf&#39;);<br>    }<br><br>    public function dompdf(Request $request): Response<br>    {<br>        $data = [<br>            &#39;invoice_number&#39; =&gt; &#39;FV/2024/05/001&#39;,<br>            &#39;date&#39; =&gt; now()-&gt;toDateString(),<br>            &#39;client&#39; =&gt; &#39;Jane Doe&#39;,<br>            &#39;items&#39; =&gt; [<br>                [&#39;name&#39; =&gt; &#39;Product A&#39;, &#39;qty&#39; =&gt; 3, &#39;price&#39; =&gt; 100],<br>                [&#39;name&#39; =&gt; &#39;Product B&#39;, &#39;qty&#39; =&gt; 1, &#39;price&#39; =&gt; 250],<br>            ],<br>            &#39;total&#39; =&gt; 3 * 100 + 250,<br>        ];<br>        return DomPdf::loadView(&#39;pdfs.dompdf-invoice&#39;, $data)-&gt;download(&#39;dompdf-invoice.pdf&#39;);<br>    }<br>}</pre><h3>Example Views</h3><h3>Spatie Laravel PDF (Tailwind, modern layout)</h3><p>resources/views/pdfs/layouts/pdf.blade.php:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;@yield(&#39;title&#39;, &#39;PDF&#39;)&lt;/title&gt;<br>    &lt;style&gt;<br>        body { font-family: &#39;Inter&#39;, sans-serif; }<br>    &lt;/style&gt;<br>    @yield(&#39;styles&#39;)<br>    &lt;script src=&quot;https://cdn.tailwindcss.com&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body class=&quot;bg-gray-100 p-8&quot;&gt;<br>@yield(&#39;content&#39;)<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>resources/views/pdfs/spatie-invoice.blade.php:</p><pre>@extends(&#39;pdfs.layouts.pdf&#39;)<br><br>@section(&#39;title&#39;, &#39;Invoice (Spatie Laravel PDF)&#39;)<br>@section(&#39;content&#39;)<br>&lt;div class=&quot;max-w-2xl mx-auto bg-white rounded shadow p-8&quot;&gt;<br>    &lt;div class=&quot;flex justify-between items-center mb-8&quot;&gt;<br>        &lt;div&gt;<br>            &lt;h1 class=&quot;text-2xl font-bold text-gray-800&quot;&gt;INVOICE&lt;/h1&gt;<br>            &lt;p class=&quot;text-gray-500&quot;&gt;Seller: &lt;span class=&quot;font-semibold&quot;&gt;{{ $user[&#39;name&#39;] }}&lt;/span&gt;&lt;/p&gt;<br>            &lt;p class=&quot;text-gray-500&quot;&gt;Email: {{ $user[&#39;email&#39;] }}&lt;/p&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;text-right&quot;&gt;<br>            &lt;p class=&quot;text-gray-500&quot;&gt;Date: {{ now()-&gt;toDateString() }}&lt;/p&gt;<br>            &lt;p class=&quot;text-gray-500&quot;&gt;Invoice No: INV/{{ now()-&gt;format(&#39;Y&#39;) }}/{{ now()-&gt;format(&#39;m&#39;) }}/001&lt;/p&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;table class=&quot;w-full mb-8 text-sm border&quot;&gt;<br>        &lt;thead&gt;<br>        &lt;tr class=&quot;bg-gray-200&quot;&gt;<br>            &lt;th class=&quot;p-2 border&quot;&gt;#&lt;/th&gt;<br>            &lt;th class=&quot;p-2 border text-left&quot;&gt;Item&lt;/th&gt;<br>            &lt;th class=&quot;p-2 border&quot;&gt;Quantity&lt;/th&gt;<br>            &lt;th class=&quot;p-2 border&quot;&gt;Unit Price&lt;/th&gt;<br>            &lt;th class=&quot;p-2 border&quot;&gt;Total&lt;/th&gt;<br>        &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>        @foreach($items as $i =&gt; $item)<br>        &lt;tr class=&quot;border-b&quot;&gt;<br>            &lt;td class=&quot;p-2 border text-center&quot;&gt;{{ $i+1 }}&lt;/td&gt;<br>            &lt;td class=&quot;p-2 border&quot;&gt;{{ $item[&#39;name&#39;] }}&lt;/td&gt;<br>            &lt;td class=&quot;p-2 border text-center&quot;&gt;{{ $item[&#39;qty&#39;] }}&lt;/td&gt;<br>            &lt;td class=&quot;p-2 border text-right&quot;&gt;${{ number_format($item[&#39;price&#39;], 2) }}&lt;/td&gt;<br>            &lt;td class=&quot;p-2 border text-right&quot;&gt;${{ number_format($item[&#39;qty&#39;] * $item[&#39;price&#39;], 2) }}&lt;/td&gt;<br>        &lt;/tr&gt;<br>        @endforeach<br>        &lt;/tbody&gt;<br>        &lt;tfoot&gt;<br>        &lt;tr&gt;<br>            &lt;td colspan=&quot;4&quot; class=&quot;p-2 border text-right font-bold&quot;&gt;Total&lt;/td&gt;<br>            &lt;td class=&quot;p-2 border text-right font-bold&quot;&gt;${{ number_format($total, 2) }}&lt;/td&gt;<br>        &lt;/tr&gt;<br>        &lt;/tfoot&gt;<br>    &lt;/table&gt;<br>    &lt;div class=&quot;text-xs text-gray-400 mt-8&quot;&gt;Generated automatically by Spatie Laravel PDF + TailwindCSS&lt;/div&gt;<br>&lt;/div&gt;<br>@endsection</pre><h3>DomPDF (simple layout)</h3><p>resources/views/pdfs/dompdf-invoice.blade.php:</p><pre>@extends(&#39;pdfs.layouts.pdf&#39;)<br><br>@section(&#39;title&#39;, &#39;Invoice (Spatie Laravel PDF)&#39;)<br>@section(&#39;styles&#39;)<br>&lt;style&gt;<br>    body { font-family: DejaVu Sans, sans-serif; }<br>    table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }<br>    th, td { border: 1px solid #ccc; padding: 6px 10px; }<br>    th { background: #eee; }<br>    .text-right { text-align: right; }<br>    .text-center { text-align: center; }<br>&lt;/style&gt;<br>@endsection<br>@section(&#39;content&#39;)<br>&lt;body&gt;<br>&lt;h2&gt;INVOICE (DomPDF)&lt;/h2&gt;<br>&lt;p&gt;Invoice No: &lt;strong&gt;{{ $invoice_number }}&lt;/strong&gt;&lt;/p&gt;<br>&lt;p&gt;Date: &lt;strong&gt;{{ $date }}&lt;/strong&gt;&lt;/p&gt;<br>&lt;p&gt;Client: &lt;strong&gt;{{ $client }}&lt;/strong&gt;&lt;/p&gt;<br>&lt;table&gt;<br>    &lt;thead&gt;<br>    &lt;tr&gt;<br>        &lt;th&gt;#&lt;/th&gt;<br>        &lt;th&gt;Item&lt;/th&gt;<br>        &lt;th&gt;Quantity&lt;/th&gt;<br>        &lt;th&gt;Unit Price&lt;/th&gt;<br>        &lt;th&gt;Total&lt;/th&gt;<br>    &lt;/tr&gt;<br>    &lt;/thead&gt;<br>    &lt;tbody&gt;<br>    @foreach($items as $i =&gt; $item)<br>    &lt;tr&gt;<br>        &lt;td class=&quot;text-center&quot;&gt;{{ $i+1 }}&lt;/td&gt;<br>        &lt;td&gt;{{ $item[&#39;name&#39;] }}&lt;/td&gt;<br>        &lt;td class=&quot;text-center&quot;&gt;{{ $item[&#39;qty&#39;] }}&lt;/td&gt;<br>        &lt;td class=&quot;text-right&quot;&gt;${{ number_format($item[&#39;price&#39;], 2) }}&lt;/td&gt;<br>        &lt;td class=&quot;text-right&quot;&gt;${{ number_format($item[&#39;qty&#39;] * $item[&#39;price&#39;], 2) }}&lt;/td&gt;<br>    &lt;/tr&gt;<br>    @endforeach<br>    &lt;/tbody&gt;<br>    &lt;tfoot&gt;<br>    &lt;tr&gt;<br>        &lt;td colspan=&quot;4&quot; class=&quot;text-right&quot;&gt;&lt;strong&gt;Total&lt;/strong&gt;&lt;/td&gt;<br>        &lt;td class=&quot;text-right&quot;&gt;&lt;strong&gt;${{ number_format($total, 2) }}&lt;/strong&gt;&lt;/td&gt;<br>    &lt;/tr&gt;<br>    &lt;/tfoot&gt;<br>&lt;/table&gt;<br>&lt;p style=&quot;font-size: 10px; color: #888;&quot;&gt;Generated automatically by barryvdh/laravel-dompdf&lt;/p&gt;<br>&lt;/body&gt;<br>@endsection</pre><h3>Comparison &amp; Recommendations</h3><pre><br>| Feature                  | Spatie Laravel PDF (Browsershot)  | barryvdh/laravel-dompdf |<br>|--------------------------|-----------------------------------|-------------------------|<br>| Engine                   | Headless Chrome (Puppeteer)       | DomPDF (PHP)            |<br>| Requires Chrome/Chromium | Yes                               | No                      |<br>| Styling                  | Full CSS, Tailwind, grid, flexbox | Basic CSS only          |<br>| Modern layouts           | Yes                               | Limited                 |<br>| Rendering quality        | Excellent                         | Good/Average            |<br>| Speed                    | Slower (Chrome startup)           | Fast (pure PHP)         |<br>| JS support               | Yes (limited)                     | No                      |<br>| SVG support              | Yes                               | Limited                 |<br>| Setup complexity         | Medium (Docker, Node, Chrome)     | Very easy               |<br>| Docker/CI compatibility  | Yes (with noSandbox)              | Yes                     |</pre><h3>When to use?</h3><ul><li><strong>Spatie Laravel PDF (Browsershot)</strong>: When you need beautiful, modern PDFs, want to use Tailwind, grid, flexbox, SVG, and your environment supports Chrome/Chromium (e.g., Docker, dedicated server). Use withBrowsershot() to customize options for Docker/CI.</li><li><strong>barryvdh/laravel-dompdf</strong>: When you need simple PDFs, want a quick setup, and don’t need advanced CSS or JS features (e.g., simple invoices, confirmations).</li></ul><h3>Summary</h3><p>Both solutions have their place in the Laravel ecosystem. For modern projects where design and layout flexibility matter, choose Spatie Laravel PDF (with Browsershot). For simple use-cases where speed and simplicity are key, barryvdh/laravel-dompdf is sufficient.</p><p><a href="https://github.com/Dommmin/laravel-production">Source Code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de2b0a4947d5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-definitive-guide-to-pdf-generation-in-laravel-spatie-browsershot-vs-dompdf-de2b0a4947d5">The Definitive Guide to PDF Generation in Laravel: Spatie Browsershot vs DomPDF</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Cloudflare Can Speed Up Your Website by 50% and Save You From Cyber Attacks]]></title>
            <link>https://medium.com/@Dommin/how-cloudflare-can-speed-up-your-website-by-50-and-save-you-from-cyber-attacks-a6c616cf15a3?source=rss-be410870b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6c616cf15a3</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Dominik]]></dc:creator>
            <pubDate>Tue, 27 May 2025 07:08:03 GMT</pubDate>
            <atom:updated>2025-05-27T07:08:03.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W65R10bthXT9D_gOuP-Nxg.png" /></figure><p><em>The complete guide to understanding why millions of websites trust Cloudflare for performance, security, and reliability</em></p><p>In today’s digital landscape, website performance isn’t just a nice-to-have — it’s a business-critical necessity. A single second of delay can cost you 7% of conversions, and 40% of users abandon websites that take more than 3 seconds to load. This is where Cloudflare comes in, transforming how websites deliver content and protect themselves from threats.</p><h3>What Exactly Is Cloudflare?</h3><p>Cloudflare is a content delivery network (CDN) and web security company that acts as a reverse proxy between your website visitors and your hosting server. Think of it as a global network of data centers that cache and deliver your content from the location closest to each user, while simultaneously filtering out malicious traffic.</p><p>With over 320 data centers across 120+ countries, Cloudflare processes more than 57 million HTTP requests per second — that’s roughly 4.9 billion requests per day for the average website.</p><h3>The Numbers That Matter: Performance Gains</h3><h3>Speed Improvements You Can Expect</h3><p><strong>Page Load Time Reduction:</strong></p><ul><li><strong>Average improvement: 50–60% faster loading times</strong></li><li>Websites typically see load times drop from 3–4 seconds to 1.5–2 seconds</li><li>Mobile performance improvements of up to 70%</li></ul><p><strong>Global Reach Impact:</strong></p><ul><li><strong>99.9% of the populated world is within 50ms of a Cloudflare data center</strong></li><li>Reduces latency by an average of 200–300ms for international visitors</li><li>European visitors to US-hosted sites see 400–500ms improvement</li></ul><p><strong>Bandwidth Savings:</strong></p><ul><li><strong>Reduces origin server bandwidth usage by 60–80%</strong></li><li>Image optimization can reduce file sizes by 35–50%</li><li>Brotli compression achieves 15–25% better compression than traditional gzip</li></ul><h3>Real-World Performance Metrics</h3><p>Companies using Cloudflare report:</p><ul><li><strong>23% increase in conversion rates</strong> due to improved page speeds</li><li><strong>19% reduction in bounce rates</strong></li><li><strong>31% improvement in Core Web Vitals scores</strong></li><li><strong>42% decrease in Time to First Byte (TTFB)</strong></li></ul><h3>Security: Your Digital Bodyguard</h3><h3>DDoS Protection That Actually Works</h3><p>Cloudflare automatically mitigates DDoS attacks, handling:</p><ul><li><strong>117 billion cyber threats per day</strong></li><li>Attacks as large as <strong>3.8 Tbps</strong> (yes, terabits per second)</li><li><strong>Zero downtime</strong> for 99.96% of websites under attack</li></ul><h3>Web Application Firewall (WAF)</h3><p>The built-in WAF blocks:</p><ul><li><strong>76 billion threats monthly</strong> across all customers</li><li>SQL injection attempts</li><li>Cross-site scripting (XSS) attacks</li><li>OWASP Top 10 vulnerabilities automatically</li></ul><h3>HTTP to HTTPS: The Security Game-Changer</h3><p>One of Cloudflare’s most valuable features is <strong>automatic HTTPS redirection</strong>. Here’s why this matters:</p><h3>The HTTPS Advantage</h3><ul><li><strong>Free SSL certificates</strong> for all domains (worth $100–300/year elsewhere)</li><li><strong>Automatic certificate renewal</strong> — never worry about expiration again</li><li><strong>TLS 1.3 support</strong> for 30% faster encryption handshakes</li><li><strong>HSTS (HTTP Strict Transport Security)</strong> prevents downgrade attacks</li></ul><h3>SEO and Trust Benefits</h3><ul><li><strong>Google ranking boost</strong> — HTTPS is a confirmed ranking factor</li><li><strong>Browser trust indicators</strong> — no more “Not Secure” warnings</li><li><strong>User confidence</strong> — 93% of users expect HTTPS on websites handling personal data</li></ul><p>Setting up HTTPS redirect takes literally 3 clicks:</p><ol><li>Enable “Always Use HTTPS” in SSL/TLS settings</li><li>Set SSL mode to “Full” or “Full (Strict)”</li><li>Enable “Automatic HTTPS Rewrites”</li></ol><h3>Features Worth Using (Beyond the Basics)</h3><h3>1. Image Optimization (Polish &amp; Mirage)</h3><ul><li><strong>Automatic image compression</strong> without quality loss</li><li><strong>WebP format conversion</strong> for 25–35% smaller file sizes</li><li><strong>Lazy loading</strong> reduces initial page load by 40–60%</li></ul><h3>2. Rocket Loader</h3><ul><li><strong>Defers JavaScript loading</strong> until after page render</li><li>Improves perceived page speed by <strong>30–50%</strong></li><li>Particularly effective for sites with heavy JavaScript frameworks</li></ul><h3>3. Browser Cache TTL</h3><ul><li><strong>Extends browser caching</strong> from hours to months</li><li>Reduces repeat visitor load times by <strong>80–90%</strong></li><li>Customizable cache rules for different file types</li></ul><h3>4. Argo Smart Routing</h3><ul><li><strong>Intelligently routes traffic</strong> through less congested paths</li><li>Improves performance by an additional <strong>30%</strong> on average</li><li>Costs $5/month but pays for itself in improved user experience</li></ul><h3>5. Workers (Serverless Computing)</h3><ul><li><strong>Run code at the edge</strong> without managing servers</li><li><strong>Sub-millisecond response times</strong> for dynamic content</li><li>Perfect for A/B testing, personalization, and API responses</li></ul><h3>The Free Tier: Surprisingly Generous</h3><p>Cloudflare’s free plan includes:</p><ul><li><strong>Unlimited bandwidth</strong> (yes, really unlimited)</li><li><strong>DDoS protection</strong> up to several gigabits</li><li><strong>3 Page Rules</strong> for custom caching and redirects</li><li><strong>Free SSL certificate</strong> with automatic renewal</li><li><strong>Basic analytics</strong> and security insights</li></ul><p>This free tier alone can handle most small to medium websites without any cost.</p><h3>Real-World Success Stories</h3><p><strong>E-commerce Site Case Study:</strong></p><ul><li>47% improvement in page load speed</li><li>23% increase in conversion rate</li><li>89% reduction in bot traffic</li><li>$47,000 additional monthly revenue attributed to performance improvements</li></ul><p><strong>News Website:</strong></p><ul><li>52% faster article loading</li><li>34% increase in page views per session</li><li>67% reduction in server costs due to caching</li><li>99.99% uptime during traffic spikes</li></ul><h3>Getting Started: The 15-minute Setup</h3><ol><li><strong>Sign up</strong> at cloudflare.com (free)</li><li><strong>Add your domain</strong> and let Cloudflare scan DNS records</li><li><strong>Update nameservers</strong> at your domain registrar</li><li><strong>Configure SSL/TLS</strong> settings (enable “Always Use HTTPS”)</li><li><strong>Enable performance features</strong> (Auto Minify, Brotli compression)</li><li><strong>Set up Page Rules</strong> for caching optimization</li></ol><h3>Common Myths Debunked</h3><p><strong>“CDNs are only for large websites”</strong> False. Even small blogs see 30–40% performance improvements.</p><p><strong>“It’s complicated to set up”</strong> The entire process takes 15–20 minutes, mostly waiting for DNS propagation.</p><p><strong>“Free tier has hidden limitations”</strong> Cloudflare’s free tier genuinely has no bandwidth limits or hidden fees.</p><h3>Monitoring Your Success</h3><p>Track these metrics after implementing Cloudflare:</p><ul><li><strong>Page load speed</strong> (aim for under 2 seconds)</li><li><strong>Core Web Vitals</strong> scores in Google Search Console</li><li><strong>Bounce rate</strong> improvements</li><li><strong>Conversion rate</strong> changes</li><li><strong>Server bandwidth</strong> usage reduction</li></ul><h3>The Bottom Line</h3><p>Cloudflare isn’t just about making websites faster — though the 50–60% speed improvements are compelling enough. It’s about creating a more secure, reliable, and user-friendly web presence that can withstand both traffic spikes and cyber attacks.</p><p>With over 26 million domains trusting Cloudflare, including major brands like Discord, Shopify, and Medium itself, the service has proven itself at every scale. The combination of performance gains, security features, and cost savings (especially considering the free tier) makes Cloudflare one of the few no-brainer decisions in web development.</p><p>Whether you’re running a personal blog or a multi-million dollar e-commerce platform, the question isn’t whether you should use Cloudflare — it’s whether you can afford not to.</p><p><em>Ready to supercharge your website? Start with Cloudflare’s free tier today and experience the difference that global edge computing can make for your online presence.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6c616cf15a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Nginx Guide: From Basics to Advanced Configuration]]></title>
            <link>https://blog.devops.dev/the-complete-nginx-guide-from-basics-to-advanced-configuration-852fbf72cf20?source=rss-be410870b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/852fbf72cf20</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Dominik]]></dc:creator>
            <pubDate>Tue, 20 May 2025 07:07:18 GMT</pubDate>
            <atom:updated>2025-05-21T15:43:01.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctbuIFxc5A6ouTsRmQn5cg.png" /></figure><h3>Introduction</h3><p>Nginx (pronounced “engine-x”) is a powerful, high-performance web server that has become the de facto standard for serving web applications. This guide will take you through everything you need to know about Nginx, from basic concepts to advanced configurations, with a special focus on PHP/Laravel applications.</p><h3>What is Nginx?</h3><p>Nginx is an open-source web server that can also be used as a reverse proxy, load balancer, and HTTP cache. It was created by Igor Sysoev and publicly released in 2004. Nginx is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.</p><h3>Why Choose Nginx?</h3><ul><li>High performance and low memory usage</li><li>Excellent handling of concurrent connections</li><li>Built-in load balancing capabilities</li><li>Strong security features</li><li>Extensive documentation and community support</li></ul><h3>Basic Concepts</h3><h3>Key Components</h3><ol><li><strong>Directives</strong>: Configuration commands that control Nginx’s behavior</li><li><strong>Contexts</strong>: Blocks that group related directives</li><li><strong>Events</strong>: How Nginx handles connections</li><li><strong>HTTP</strong>: Web server configuration</li><li><strong>Server</strong>: Virtual host configuration</li><li><strong>Location</strong>: URL matching and handling</li></ol><h3>Basic Configuration Structure</h3><pre># Main context<br>user www-data;<br>worker_processes auto;<br>error_log /var/log/nginx/error.log;<br>pid /run/nginx.pid;<br><br># Events context<br>events {<br>    worker_connections 1024;<br>}<br># HTTP context<br>http {<br>    # Basic settings<br>    sendfile on;<br>    tcp_nopush on;<br>    tcp_nodelay on;<br>    keepalive_timeout 65;<br>    types_hash_max_size 2048;<br>    # MIME types<br>    include /etc/nginx/mime.types;<br>    default_type application/octet-stream;<br>    # Logging<br>    access_log /var/log/nginx/access.log;<br>    error_log /var/log/nginx/error.log;<br>    # Server context<br>    server {<br>        listen 80;<br>        server_name example.com;<br>        root /var/www/html;<br>        # Location context<br>        location / {<br>            try_files $uri $uri/ /index.php?$query_string;<br>        }<br>    }<br>}</pre><h3>Installation and Basic Setup</h3><h3>Ubuntu/Debian Installation</h3><pre># Update package list<br>sudo apt update<br><br># Install Nginx<br>sudo apt install nginx<br># Start Nginx<br>sudo systemctl start nginx<br># Enable Nginx to start on boot<br>sudo systemctl enable nginx<br># Check status<br>sudo systemctl status nginx</pre><h3>Basic Configuration File Structure</h3><pre>/etc/nginx/<br>├── nginx.conf          # Main configuration file<br>├── sites-available/    # Available site configurations<br>├── sites-enabled/      # Enabled site configurations<br>├── conf.d/            # Additional configuration files<br>└── snippets/          # Reusable configuration snippets</pre><h3>Configuration Structure</h3><h3>Main Configuration (nginx.conf)</h3><pre># /etc/nginx/nginx.conf<br>user www-data;<br>worker_processes auto;<br>pid /run/nginx.pid;<br><br>events {<br>    worker_connections 1024;<br>    multi_accept on;<br>}<br><br>http {<br>    # Basic Settings<br>    sendfile on;<br>    tcp_nopush on;<br>    tcp_nodelay on;<br>    keepalive_timeout 65;<br>    types_hash_max_size 2048;<br>    # MIME Types<br>    include /etc/nginx/mime.types;<br>    default_type application/octet-stream;<br>    # Logging<br>    access_log /var/log/nginx/access.log;<br>    error_log /var/log/nginx/error.log;<br>    # Gzip Settings<br>    gzip on;<br>    gzip_vary on;<br>    gzip_proxied any;<br>    gzip_comp_level 6;<br>    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;<br>    # Virtual Host Configs<br>    include /etc/nginx/conf.d/*.conf;<br>    include /etc/nginx/sites-enabled/*;<br>}</pre><h3>Virtual Host Configuration</h3><pre># /etc/nginx/sites-available/example.com<br>server {<br>    listen 80;<br>    server_name example.com www.example.com;<br>    root /var/www/example.com/public;<br>    index index.php index.html;<br><br>    # Security headers<br>    add_header X-Frame-Options &quot;SAMEORIGIN&quot;;<br>    add_header X-Content-Type-Options &quot;nosniff&quot;;<br>    add_header X-XSS-Protection &quot;1; mode=block&quot;;<br><br>    # Logging<br>    access_log /var/log/nginx/example.com.access.log;<br>    error_log /var/log/nginx/example.com.error.log;<br><br>    location / {<br>        try_files $uri $uri/ /index.php?$query_string;<br>    }<br><br>    location ~ \.php$ {<br>        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;<br>        fastcgi_index index.php;<br>        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;<br>        include fastcgi_params;<br>    }<br>}</pre><h3>Common Use Cases</h3><h3>1. Static File Serving</h3><pre>location /static/ {<br>    alias /var/www/static/;<br>    expires 30d;<br>    add_header Cache-Control &quot;public, no-transform&quot;;<br>}</pre><h3>2. Load Balancing</h3><pre>upstream backend {<br>    server backend1.example.com:8080;<br>    server backend2.example.com:8080;<br>    server backend3.example.com:8080;<br>}<br><br>server {<br>    location / {<br>        proxy_pass http://backend;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>    }<br>}</pre><h3>3. SSL/TLS Configuration</h3><pre>server {<br>    listen 443 ssl http2;<br>    server_name example.com;<br><br>    ssl_certificate /etc/nginx/ssl/example.com.crt;<br>    ssl_certificate_key /etc/nginx/ssl/example.com.key;<br>    ssl_protocols TLSv1.2 TLSv1.3;<br>    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;<br>    ssl_prefer_server_ciphers off;<br>    ssl_session_timeout 1d;<br>    ssl_session_cache shared:SSL:50m;<br>    ssl_session_tickets off;<br>    ssl_stapling on;<br>    ssl_stapling_verify on;<br>    add_header Strict-Transport-Security &quot;max-age=63072000&quot; always;<br>}</pre><h3>Performance Optimization</h3><h3>1. Worker Processes and Connections</h3><pre>worker_processes auto;  # Automatically set based on CPU cores<br>worker_rlimit_nofile 65535;  # Increase file descriptor limit<br><br>events {<br>    worker_connections 1024;<br>    multi_accept on;<br>    use epoll;  # Efficient event processing method<br>}</pre><h3>2. Caching</h3><pre># FastCGI Cache<br>fastcgi_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;<br><br>location ~ \.php$ {<br>    fastcgi_cache my_cache;<br>    fastcgi_cache_valid 200 60m;<br>    fastcgi_cache_use_stale error timeout http_500 http_503;<br>    fastcgi_cache_key &quot;$request_method$request_uri&quot;;<br>}</pre><h3>3. Gzip Compression</h3><p>Gzip compression reduces the size of files sent from the server to the client, which can significantly decrease the time it takes for a web page to load. This is especially beneficial for users with slower internet connections. By enabling gzip, you can improve the performance and speed of your website.</p><h3>Security Headers</h3><ol><li><strong>X-Frame-Options</strong>: This header helps prevent clickjacking attacks by controlling whether a browser should be allowed to render a page in a &lt;frame&gt;, &lt;iframe&gt;, &lt;embed&gt;, or &lt;object&gt;. Setting it to SAMEORIGIN allows the page to be displayed only on the same origin as the page itself.</li><li><strong>X-Content-Type-Options</strong>: This header prevents browsers from MIME-sniffing a response away from the declared content-type. Setting it to nosniff helps prevent attacks based on MIME-type confusion.</li><li><strong>X-XSS-Protection</strong>: This header enables the Cross-Site Scripting (XSS) filter built into most modern web browsers. Setting it to 1; mode=block will block the page if an XSS attack is detected.</li><li><strong>Referrer-Policy</strong>: This header controls how much referrer information should be included with requests. Setting it to strict-origin-when-cross-origin provides a good balance between security and usability.</li></ol><h3>Client Body and Header Timeouts</h3><p>These settings control how long the server will wait for a client to send the body and headers of a request. By setting appropriate timeouts, you can prevent slow clients from holding connections open indefinitely, which can help protect against certain types of denial-of-service (DoS) attacks.</p><h3>Proxy Settings for WebSockets</h3><p>When using Nginx as a reverse proxy for WebSocket connections, it’s important to set the appropriate headers and timeouts to ensure that the connection remains open and responsive. The proxy_set_header directives ensure that the correct headers are passed to the backend server, while the proxy_read_timeout, proxy_send_timeout, and proxy_connect_timeout settings help maintain a stable connection.</p><h3>Security Best Practices</h3><h3>1. Basic Security Headers</h3><pre>add_header X-Frame-Options &quot;SAMEORIGIN&quot; always;<br>add_header X-XSS-Protection &quot;1; mode=block&quot; always;<br>add_header X-Content-Type-Options &quot;nosniff&quot; always;<br>add_header Referrer-Policy &quot;no-referrer-when-downgrade&quot; always;<br>add_header Content-Security-Policy &quot;default-src &#39;self&#39; http: https: data: blob: &#39;unsafe-inline&#39;&quot; always;<br>add_header Strict-Transport-Security &quot;max-age=31536000; includeSubDomains&quot; always;</pre><h3>2. Rate Limiting</h3><pre>limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;<br><br>server {<br>    location /login {<br>        limit_req zone=one burst=5 nodelay;<br>        proxy_pass http://backend;<br>    }<br>}</pre><h3>3. SSL Configuration</h3><pre>ssl_protocols TLSv1.2 TLSv1.3;<br>ssl_prefer_server_ciphers on;<br>ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;</pre><h3>PHP/Laravel Integration</h3><h3>1. Standard Installation (Without Docker)</h3><pre># /etc/nginx/sites-available/laravel<br>server {<br>    listen 80;<br>    server_name laravel.example.com;<br>    root /var/www/laravel/public;<br><br>    add_header X-Frame-Options &quot;SAMEORIGIN&quot;;<br>    add_header X-Content-Type-Options &quot;nosniff&quot;;<br>    index index.php;<br>    charset utf-8;<br><br>    location / {<br>        try_files $uri $uri/ /index.php?$query_string;<br>    }<br><br>    location = /favicon.ico { access_log off; log_not_found off; }<br>    location = /robots.txt  { access_log off; log_not_found off; }<br><br>    error_page 404 /index.php;<br><br>    location ~ \.php$ {<br>        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;<br>        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;<br>        include fastcgi_params;<br>    }<br><br>    location ~ /\.(?!well-known).* {<br>        deny all;<br>    }<br>}</pre><h3>2. Docker Integration</h3><pre># docker/nginx/conf.d/default.conf<br>server {<br>    listen 80;<br>    server_name _;<br>    root /var/www/public;<br><br>    index index.php index.html;<br><br>    charset utf-8;<br>    client_max_body_size 100M;<br>    client_body_buffer_size 100M;<br>    client_body_timeout 60s;<br>    client_header_timeout 60s;<br>    send_timeout 60s;<br><br>    # Gzip compression<br>    gzip on;<br>    gzip_vary on;<br>    gzip_min_length 10240;<br>    gzip_proxied expired no-cache no-store private auth;<br>    gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml application/javascript;<br>    gzip_disable &quot;MSIE [1-6]\.&quot;;<br><br>    # Security headers<br>    add_header X-Frame-Options &quot;SAMEORIGIN&quot;;<br>    add_header X-Content-Type-Options &quot;nosniff&quot;;<br>    add_header X-XSS-Protection &quot;1; mode=block&quot;;<br>    add_header Referrer-Policy &quot;strict-origin-when-cross-origin&quot;;<br>    <br>    # Logs<br>    access_log /var/www/storage/logs/nginx_access.log;<br>    error_log /var/www/storage/logs/nginx_error.log;<br><br>    location / {<br>        try_files $uri $uri/ /index.php?$query_string;<br>    }<br><br>    # Storage files<br>    location ^~ /storage/ {<br>        alias /var/www/storage/app/public/;<br>        try_files $uri $uri/ =404;<br>        expires 30d;<br>        add_header Cache-Control &quot;public, no-transform&quot;;<br>        add_header X-Content-Type-Options &quot;nosniff&quot;;<br>    }<br><br>    # Build assets<br>    location /build/ {<br>        alias /var/www/public/build/;<br>        add_header Cache-Control &quot;public, max-age=31536000, immutable&quot;;<br>        add_header X-Content-Type-Options &quot;nosniff&quot;;<br>        try_files $uri =404;<br>    }<br><br>    # PHP handling<br>    location ~ \.php$ {<br>        fastcgi_pass app:9000;<br>        fastcgi_index index.php;<br>        include fastcgi_params;<br>        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;<br>        fastcgi_param PATH_INFO $fastcgi_path_info;<br>        fastcgi_buffers 16 16k;<br>        fastcgi_buffer_size 32k;<br>        fastcgi_read_timeout 600;<br>        fastcgi_send_timeout 600;<br>    }<br><br>    # Static files<br>    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {<br>        expires max;<br>        log_not_found off;<br>        add_header Cache-Control &quot;public, max-age=31536000, immutable&quot;;<br>        add_header X-Content-Type-Options &quot;nosniff&quot;;<br>    }<br><br>    # Deny access to sensitive files<br>    location ~ /\.(?!well-known).* {<br>        deny all;<br>    }<br><br>    location ~ /\.env {<br>        deny all;<br>    }<br><br>    location ~ /\.git {<br>        deny all;<br>    }<br>}</pre><h3>Troubleshooting</h3><h3>Common Issues and Solutions</h3><ol><li><strong>502 Bad Gateway</strong></li></ol><ul><li>Check if PHP-FPM is running</li><li>Verify socket file exists</li><li>Check permissions</li></ul><p>2. <strong>404 Not Found</strong></p><ul><li>Verify root directory path</li><li>Check file permissions</li><li>Ensure try_files directive is correct</li></ul><p>3. <strong>Permission Issues</strong></p><pre># Fix permissions for Laravel <br>sudo chown -R www-data:www-data /var/www/laravel <br>sudo chmod -R 755 /var/www/laravel <br>sudo chmod -R 775 /var/www/laravel/storage <br>sudo chmod -R 775 /var/www/laravel/bootstrap/cache</pre><h3>Useful Commands</h3><pre># Test configuration<br>nginx -t<br><br># Reload configuration<br>sudo systemctl reload nginx<br><br># Check error logs<br>tail -f /var/log/nginx/error.log<br><br># Check access logs<br>tail -f /var/log/nginx/access.log</pre><h3>Conclusion</h3><p>Nginx is a powerful and flexible web server that can handle various use cases, from serving static files to complex load balancing scenarios. By following the best practices outlined in this guide, you can create a secure, performant, and maintainable web server configuration for your PHP/Laravel applications.</p><p>Remember to:</p><ul><li>Always test configurations before applying them</li><li>Keep security in mind</li><li>Monitor performance</li><li>Regularly update Nginx and its modules</li><li>Back up your configurations</li></ul><h3>Additional Resources</h3><ul><li><a href="https://nginx.org/en/docs/">Official Nginx Documentation</a></li><li><a href="https://www.nginx.com/resources/wiki/">Nginx Wiki</a></li><li><a href="https://laravel.com/docs">Laravel Documentation</a></li><li><a href="https://www.digitalocean.com/community/tags/nginx">DigitalOcean Nginx Tutorials</a></li></ul><h3>Basic Authentication</h3><p>Basic authentication can be used to restrict access to certain parts of your website. To set up basic authentication in Nginx, follow these steps:</p><ol><li><strong>Create a Password File</strong></li></ol><ul><li>Use the htpasswd command to create a password file:</li></ul><pre>sudo htpasswd -c /etc/nginx/.htpasswd username</pre><ul><li>You will be prompted to enter a password for the user.</li></ul><ol><li><strong>Update Nginx Configuration</strong></li></ol><ul><li>Add the following lines to your server block in the Nginx configuration:</li></ul><pre>location / {<br>     auth_basic &quot;Restricted Content&quot;;<br>     auth_basic_user_file /etc/nginx/.htpasswd;<br>     try_files $uri $uri/ /index.php?$query_string;<br> }</pre><p>2. <strong>Reload Nginx</strong></p><ul><li>After updating the configuration, reload Nginx to apply the changes:</li></ul><pre>sudo systemctl reload nginx</pre><p>This setup will prompt users to enter a username and password when accessing the restricted area.</p><h3>Installing apache2-utils</h3><p>To use the htpasswd command for creating password files, you need to install the apache2-utils package. This can be done with the following command:</p><pre>sudo apt install apache2-utils</pre><h3>Handling .htpasswd in Docker</h3><p>To generate the .htpasswd file during the build, you can add a command like this to your Dockerfile:</p><pre>htpasswd -bc /etc/nginx/.htpasswd username password</pre><p>Replace username and password with your desired credentials. This command installs apache2-utils and creates the .htpasswd file with the specified user credentials.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=852fbf72cf20" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/the-complete-nginx-guide-from-basics-to-advanced-configuration-852fbf72cf20">The Complete Nginx Guide: From Basics to Advanced Configuration</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Robust File Import System in Laravel with Real-Time Progress Updates]]></title>
            <link>https://levelup.gitconnected.com/building-a-robust-file-import-system-in-laravel-with-real-time-progress-updates-3011b8229170?source=rss-be410870b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3011b8229170</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Dominik]]></dc:creator>
            <pubDate>Mon, 19 May 2025 07:31:39 GMT</pubDate>
            <atom:updated>2025-05-20T11:56:19.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ccBschRhHiiznKb1mj2Aw.png" /></figure><h3>Prerequisites</h3><p>Before we begin, ensure you have installed the necessary package, Laravel Excel, which will be used for handling the import of CSV/Excel files. You can install it via Composer:</p><pre>composer require maatwebsite/excel</pre><p>This package provides a simple and elegant way to import and export Excel and CSV files in Laravel.</p><p>In this article, I’ll walk you through creating a robust file import system in Laravel that handles large CSV/Excel files, provides real-time progress updates, and manages validation errors effectively. We’ll use Laravel Excel, Laravel Broadcasting, and React for the frontend.</p><h3>Table of Contents</h3><ol><li>Setting Up the Foundation</li><li>Creating the Import Job System</li><li>Implementing the Import Logic</li><li>Real-Time Progress Updates</li><li>Frontend Implementation</li><li>Error Handling and User Feedback</li></ol><h3>1. Setting Up the Foundation</h3><p>First, let’s set up our database structure. We need two main tables: contacts (for our imported data) and import_jobs (to track import progress).</p><pre>// Migration for import_jobs table<br>Schema::create(&#39;import_jobs&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;enum(&#39;status&#39;, ImportJobEnum::values())-&gt;default(ImportJobEnum::STATUS_PENDING-&gt;value);<br>    $table-&gt;json(&#39;errors&#39;)-&gt;nullable();<br>    $table-&gt;integer(&#39;total_rows&#39;)-&gt;default(0);<br>    $table-&gt;integer(&#39;processed_rows&#39;)-&gt;default(0);<br>    $table-&gt;string(&#39;filename&#39;);<br>    $table-&gt;timestamps();<br>});</pre><p>We also create an enum to manage import job statuses:</p><pre>enum ImportJobEnum: string<br>{<br>    case STATUS_PENDING = &#39;pending&#39;;<br>    case STATUS_COMPLETED = &#39;completed&#39;;<br>    case STATUS_FAILED = &#39;failed&#39;;<br><br>    public static function values(): array<br>    {<br>        return [<br>            self::STATUS_PENDING-&gt;value,<br>            self::STATUS_COMPLETED-&gt;value,<br>            self::STATUS_FAILED-&gt;value,<br>        ];<br>    }<br>}</pre><h3>2. Creating the Import Job System</h3><p>The ImportJob model tracks the progress of each import:</p><pre>class ImportJob extends Model<br>{<br>    protected $fillable = [<br>      &#39;status&#39;,<br>      &#39;errors&#39;,<br>      &#39;total_rows&#39;,<br>      &#39;processed_rows&#39;,<br>      &#39;filename&#39;,<br>    ];<br><br>    protected $casts = [<br>      &#39;errors&#39; =&gt; &#39;array&#39;,<br>      &#39;status&#39; =&gt; ImportJobEnum::class,<br>    ];<br><br>    public function hasErrors(): bool<br>    {<br>        return (bool) $this-&gt;errors;<br>    }<br>}</pre><h3>3. Implementing the Import Logic</h3><p>We use Laravel Excel’s import functionality with chunk processing for better performance:</p><pre>&lt;?php<br><br>declare(strict_types=1);<br><br>namespace App\Imports;<br><br>use App\DTO\ContactData;<br>use App\Enums\ImportJobEnum;<br>use App\Events\ContactImportError;<br>use App\Events\ContactImportFailed;<br>use App\Events\ContactImportFinished;<br>use App\Models\Contact;<br>use App\Models\ImportJob;<br>use App\Repositories\ImportJobRepository;<br>use Illuminate\Contracts\Queue\ShouldQueue;<br>use Illuminate\Support\Facades\Log;<br>use Maatwebsite\Excel\Concerns\Importable;<br>use Maatwebsite\Excel\Concerns\RegistersEventListeners;<br>use Maatwebsite\Excel\Concerns\SkipsOnError;<br>use Maatwebsite\Excel\Concerns\SkipsOnFailure;<br>use Maatwebsite\Excel\Concerns\ToModel;<br>use Maatwebsite\Excel\Concerns\WithBatchInserts;<br>use Maatwebsite\Excel\Concerns\WithChunkReading;<br>use Maatwebsite\Excel\Concerns\WithEvents;<br>use Maatwebsite\Excel\Concerns\WithHeadingRow;<br>use Maatwebsite\Excel\Concerns\WithValidation;<br>use Maatwebsite\Excel\Events\AfterImport;<br>use Maatwebsite\Excel\Validators\Failure;<br>use Throwable;<br><br>class ContactsImport implements ShouldQueue, SkipsOnError, SkipsOnFailure, ToModel, WithBatchInserts, WithChunkReading, WithEvents, WithHeadingRow, WithValidation<br>{<br>    use Importable;<br>    use RegistersEventListeners;<br><br>    private array $failures = [];<br>    private ImportJob $importJob;<br><br>    public function __construct(<br>        string $filename,<br>        private readonly ImportJobRepository $importJobRepository,<br>    ) {<br>        $this-&gt;importJob = $this-&gt;importJobRepository-&gt;create($filename);<br>    }<br><br>    public function model(array $row): Contact<br>    {<br>        $this-&gt;importJobRepository-&gt;incrementProcessedRows($this-&gt;importJob);<br>        $row[&#39;phone&#39;] = isset($row[&#39;phone&#39;]) ? (string) $row[&#39;phone&#39;] : null;<br>        $contactData = ContactData::fromArray($row);<br>        return new Contact($contactData-&gt;toArray());<br>    }<br><br>    public function rules(): array<br>    {<br>        return [<br>            &#39;name&#39; =&gt; [&#39;required&#39;, &#39;string&#39;, &#39;max:255&#39;],<br>            &#39;email&#39; =&gt; [&#39;required&#39;, &#39;email&#39;, &#39;unique:contacts,email&#39;, &#39;max:255&#39;],<br>            &#39;phone&#39; =&gt; [&#39;nullable&#39;],<br>            &#39;company&#39; =&gt; [&#39;nullable&#39;, &#39;string&#39;, &#39;max:255&#39;],<br>        ];<br>    }<br><br>    public function onFailure(Failure ...$failures): void<br>    {<br>        $this-&gt;failures = array_merge($this-&gt;failures, $failures);<br>        $totalFailures = count($this-&gt;failures);<br>        $formattedFailures = array_map(function (Failure $failure) {<br>            return [<br>                &#39;row&#39; =&gt; $failure-&gt;row(),<br>                &#39;attribute&#39; =&gt; $failure-&gt;attribute(),<br>                &#39;errors&#39; =&gt; $failure-&gt;errors(),<br>            ];<br>        }, $failures);<br>        $maxErrorsToShow = config(&#39;import.max_errors_to_show&#39;);<br>        $errorsToShow = array_slice($formattedFailures, 0, $maxErrorsToShow);<br>        if ($totalFailures &gt; $maxErrorsToShow) {<br>            $errorsToShow[] = [<br>                &#39;row&#39; =&gt; null,<br>                &#39;attribute&#39; =&gt; null,<br>                &#39;errors&#39; =&gt; [&#39;And &#39;.($totalFailures - $maxErrorsToShow).&#39; more validation errors&#39;],<br>            ];<br>        }<br>        $this-&gt;importJobRepository-&gt;updateErrors($this-&gt;importJob, $errorsToShow);<br>        event(new ContactImportFailed($errorsToShow, $this-&gt;importJob-&gt;id));<br>    }<br><br>    public function onError(Throwable $e): void<br>    {<br>        Log::error(&#39;Error importing contacts&#39;, [<br>            &#39;message&#39; =&gt; $e-&gt;getMessage(),<br>            &#39;trace&#39; =&gt; $e-&gt;getTraceAsString(),<br>            &#39;line&#39; =&gt; $e-&gt;getLine(),<br>            &#39;import_job_id&#39; =&gt; $this-&gt;importJob-&gt;id,<br>        ]);<br>        $this-&gt;importJobRepository-&gt;updateStatus($this-&gt;importJob, ImportJobEnum::STATUS_FAILED);<br>        $this-&gt;importJobRepository-&gt;updateErrors($this-&gt;importJob, [[<br>            &#39;message&#39; =&gt; $e-&gt;getMessage(),<br>            &#39;line&#39; =&gt; $e-&gt;getLine(),<br>        ]]);<br>        event(new ContactImportError($this-&gt;importJob-&gt;id));<br>    }<br>    public function chunkSize(): int<br>    {<br>        return config(&#39;import.chunk_size&#39;);<br>    }<br><br>    public function batchSize(): int<br>    {<br>        return config(&#39;import.chunk_size&#39;);<br>    }<br><br>    public function registerEvents(): array<br>    {<br>        return [<br>            AfterImport::class =&gt; function (AfterImport $event) {<br>                $importJob = $this-&gt;importJobRepository-&gt;find($this-&gt;importJob-&gt;id);<br>                if (! $importJob) {<br>                    return;<br>                }<br>                $status = $importJob-&gt;hasErrors()<br>                    ? ImportJobEnum::STATUS_FAILED<br>                    : ImportJobEnum::STATUS_COMPLETED;<br>                $this-&gt;importJobRepository-&gt;updateStatus($importJob, $status);<br>                if ($status === ImportJobEnum::STATUS_COMPLETED) {<br>                    event(new ContactImportFinished($importJob-&gt;id));<br>                }<br>            },<br>        ];<br>    }<br>}</pre><h3>4. Real-Time Progress Updates</h3><p>We implement three events for real-time updates:</p><pre>class ContactImportFinished implements ImportEvent, ShouldBroadcastNow<br>{<br>    use Dispatchable;<br>    use InteractsWithSockets;<br>    use SerializesModels;<br><br>public function __construct(<br>        private readonly int $importJobId,<br>    ) {}<br><br>    public function broadcastOn(): Channel<br>    {<br>        return new Channel(&#39;imports&#39;);<br>    }<br><br>    public function broadcastAs(): string<br>    {<br>        return &#39;ContactImportFinished&#39;;<br>    }<br><br>    public function getImportJobId(): int<br>    {<br>        return $this-&gt;importJobId;<br>    }<br><br>    public function getTimestamp(): Carbon<br>    {<br>        return now();<br>    }<br>}<br><br>class ContactImportFailed implements ShouldBroadcastNow<br>{<br>    use Dispatchable, InteractsWithSockets, SerializesModels;<br><br>    public array $failures = [];<br>    private int $importJobId;<br><br>    public function __construct(array $failures, int $importJobId)<br>    {<br>        $this-&gt;failures = $failures;<br>        $this-&gt;importJobId = $importJobId;<br>    }<br><br>    public function broadcastOn()<br>    {<br>        return new Channel(&#39;imports&#39;);<br>    }<br><br>    public function broadcastAs(): string<br>    {<br>        return &#39;ContactImportFailed&#39;;<br>    }<br><br>    public function broadcastWith(): array<br>    {<br>        return [<br>            &#39;failures&#39; =&gt; $this-&gt;failures,<br>            &#39;importJobId&#39; =&gt; $this-&gt;importJobId,<br>        ];<br>    }<br>}<br>class ContactImportError implements ShouldBroadcastNow<br>{<br>    use Dispatchable, InteractsWithSockets, SerializesModels;<br><br>    public function __construct(<br>        private readonly int $importJobId,<br>    ) {}<br><br>    public function broadcastOn()<br>    {<br>        return new Channel(&#39;imports&#39;);<br>    }<br><br>    public function broadcastAs(): string<br>    {<br>        return &#39;ContactImportError&#39;;<br>    }<br><br>    public function broadcastWith(): array<br>    {<br>        return [<br>            &#39;message&#39; =&gt; &#39;An error occurred during the import&#39;,<br>            &#39;importJobId&#39; =&gt; $this-&gt;importJobId,<br>        ];<br>    }<br>}</pre><h3>5. Frontend Implementation</h3><p>Our React component handles file uploads and displays real-time progress:</p><pre>export default function ContactsIndex({ contacts }: { contacts: ContactData }) {<br>    const { setData, post, processing, errors } = useForm&lt;FormData&gt;({<br>        file: null,<br>    });<br>    const [importing, setImporting] = useState(false);<br>    const [importErrors, setImportErrors] = useState&lt;string[]&gt;([]);<br><br>    const formatImportError = (error: ImportError): string =&gt; {<br>        const parts: string[] = [];<br>        if (error.row) parts.push(`Row ${error.row}`);<br>        if (error.errors &amp;&amp; error.errors.length &gt; 0) {<br>            parts.push(error.errors.join(&#39;, &#39;));<br>        }<br>        return parts.length &gt; 0 ? parts.join(&#39; - &#39;) : &#39;Invalid data format&#39;;<br>    };<br><br>    useEffect(() =&gt; {<br>        const channel = window.Echo.channel(&#39;imports&#39;);<br>        channel.listen(&#39;.ContactImportFinished&#39;, () =&gt; {<br>            setImporting(false);<br>            setImportErrors([]);<br>            toast.success(&#39;Import finished successfully&#39;);<br>            router.reload({ only: [&#39;contacts&#39;] });<br>        })<br>            .listen(&#39;.ContactImportFailed&#39;, (event) =&gt; {<br>                setImporting(false);<br>                if (event.failures &amp;&amp; Array.isArray(event.failures)) {<br>                    const formattedErrors = event.failures.map(formatImportError);<br>                    setImportErrors(formattedErrors);<br>                    toast.error(&#39;Import failed with validation errors&#39;);<br>                } else {<br>                    toast.error(&#39;Something went wrong&#39;);<br>                }<br>                router.reload({ only: [&#39;contacts&#39;] });<br>            })<br>            .listen(&#39;.ContactImportError&#39;, () =&gt; {<br>                setImporting(false);<br>                setImportErrors([]);<br>                toast.error(&#39;Something went wrong&#39;);<br>                router.reload({ only: [&#39;contacts&#39;] });<br>            });<br>        return () =&gt; {<br>            window.Echo.leave(&#39;imports&#39;);<br>        };<br>    }, [])<br>}</pre><h3>6. Error Handling and User Feedback</h3><p>We implement smart error handling that limits the number of displayed errors to prevent overwhelming the user:</p><pre>public function onFailure(Failure ...$failures): void<br>    {<br>        $this-&gt;failures = array_merge($this-&gt;failures, $failures);<br>        $totalFailures = count($this-&gt;failures);<br><br>        $formattedFailures = array_map(function (Failure $failure) {<br>            return [<br>                &#39;row&#39; =&gt; $failure-&gt;row(),<br>                &#39;attribute&#39; =&gt; $failure-&gt;attribute(),<br>                &#39;errors&#39; =&gt; $failure-&gt;errors(),<br>            ];<br>        }, $failures);<br><br>        $maxErrorsToShow = config(&#39;import.max_errors_to_show&#39;);<br>        $errorsToShow = array_slice($formattedFailures, 0, $maxErrorsToShow);<br><br>        if ($totalFailures &gt; $maxErrorsToShow) {<br>            $errorsToShow[] = [<br>                &#39;row&#39; =&gt; null,<br>                &#39;attribute&#39; =&gt; null,<br>                &#39;errors&#39; =&gt; [&#39;And &#39;.($totalFailures - $maxErrorsToShow).&#39; more validation errors&#39;],<br>            ];<br>        }<br><br>        $this-&gt;importJobRepository-&gt;updateErrors($this-&gt;importJob, $errorsToShow);<br>        event(new ContactImportFailed($errorsToShow, $this-&gt;importJob-&gt;id));<br>    }</pre><h3>7. Source Code</h3><p><a href="https://github.com/Dommmin/laravel-production"><em>https://github.com/Dommmin/laravel-production</em></a></p><h3>Key Features of Our Implementation</h3><ol><li><strong>Chunked Processing</strong>: We process large files in chunks to prevent memory issues</li><li><strong>Real-time Updates</strong>: Users see import progress through Laravel Broadcasting</li><li><strong>Error Management</strong>: Smart error handling with limited error display</li><li><strong>Queue System</strong>: Background processing for better user experience</li><li><strong>Progress Tracking</strong>: Detailed tracking of processed rows and errors</li></ol><h3>Configuration</h3><p>We also implement specific Excel configuration for optimal performance:</p><pre>return [<br>    &#39;queue&#39; =&gt; [<br>        &#39;tries&#39; =&gt; 1,<br>        &#39;timeout&#39; =&gt; 600,<br>    ],<br>    &#39;imports&#39; =&gt; [<br>        &#39;chunk_size&#39; =&gt; 1000,<br>        &#39;read_only&#39; =&gt; true,<br>    ],<br>];</pre><h3>Conclusion</h3><p>This implementation provides a robust, user-friendly system for importing large files with real-time feedback. It handles errors gracefully, provides progress updates, and maintains a good user experience even with large datasets.</p><p>The combination of Laravel’s queuing system, Laravel Excel’s chunking capabilities, and real-time broadcasting creates a powerful and scalable import solution that can be adapted for various use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3011b8229170" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-a-robust-file-import-system-in-laravel-with-real-time-progress-updates-3011b8229170">Building a Robust File Import System in Laravel with Real-Time Progress Updates</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Telescope — Advanced Debugging and Monitoring for Laravel Applications]]></title>
            <link>https://levelup.gitconnected.com/laravel-telescope-advanced-debugging-and-monitoring-for-laravel-applications-4a3b47a3e7c4?source=rss-be410870b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a3b47a3e7c4</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dominik]]></dc:creator>
            <pubDate>Fri, 16 May 2025 07:41:55 GMT</pubDate>
            <atom:updated>2025-05-19T02:02:15.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EkbCjBnZdNc30LKKRd1vOg.png" /></figure><h3>Laravel Telescope — Advanced Debugging and Monitoring for Laravel Applications</h3><h3>Introduction</h3><p>In this article, we’ll explore the capabilities of Laravel Telescope and demonstrate how this tool can significantly improve the process of developing, testing, and maintaining Laravel applications.</p><h3>What is Laravel Telescope?</h3><p>Laravel Telescope is the official debugging tool for the Laravel framework, created by the Laravel team. It allows you to monitor various aspects of your application’s operation, including SQL queries, HTTP requests, exception handling, queue operations, and much more.</p><p>Unlike Laravel Debugbar, which operates in real-time in the browser, Telescope provides a dedicated web interface with operation history, allowing for deeper analysis and diagnostics of issues after they occur.</p><h3>Installation and Configuration</h3><pre>composer require laravel/telescope --dev</pre><p>It’s recommended to install Telescope as a development dependency (--dev) since it shouldn&#39;t be used in production environments due to performance and security considerations.</p><p>After installation, publish the resources and configuration:</p><pre>php artisan telescope:install</pre><p>This command:</p><ul><li>Publishes Telescope configuration</li><li>Creates migrations for database tables that will store Telescope data</li><li>Registers the Telescope ServiceProvider</li></ul><p>Finally, run the migrations:</p><pre>php artisan migrate</pre><p>This will create the necessary database tables for storing information collected by Telescope.</p><h3>Basic Configuration</h3><p>After installation, the config/telescope.php file contains all Telescope settings:</p><pre>&lt;?php<br><br>return [<br>    // Path to access the Telescope panel<br>    &#39;path&#39; =&gt; &#39;telescope&#39;,<br>    // Enable/disable Telescope<br>    &#39;enabled&#39; =&gt; env(&#39;TELESCOPE_ENABLED&#39;, true),<br>    // Data storage (database)<br>    &#39;storage&#39; =&gt; [<br>        &#39;database&#39; =&gt; [<br>            &#39;connection&#39; =&gt; env(&#39;DB_CONNECTION&#39;, &#39;mysql&#39;),<br>            &#39;chunk&#39; =&gt; 1000,<br>        ],<br>    ],<br>    // How long to store data (in hours)<br>    &#39;hours&#39; =&gt; 24,<br>    // Which watchers should be active<br>    &#39;watchers&#39; =&gt; [<br>        // ...<br>    ],<br>];</pre><h3>Controlling Access to Telescope Panel</h3><p>By default, Telescope is only accessible in the local environment. To allow access in other environments, modify the gate method in the TelescopeServiceProvider.php file:</p><pre>/**<br> * Register the Telescope gate.<br> *<br> * This gate determines who can access Telescope in non-local environments.<br> *<br> * @return void<br> */<br>protected function gate()<br>{<br>    Gate::define(&#39;viewTelescope&#39;, function ($user) {<br>        return in_array($user-&gt;email, [<br>            &#39;admin@example.com&#39;,<br>            &#39;developer@example.com&#39;<br>        ]);<br>    });<br>}</pre><h3>Key Features of Laravel Telescope</h3><h3>1. HTTP Request Monitoring</h3><p>Telescope records all incoming HTTP requests to your application along with their details:</p><ul><li>URL</li><li>HTTP method</li><li>Parameters</li><li>Headers</li><li>Response code</li><li>Execution time</li></ul><h3>2. Database Query Monitoring</h3><p>Telescope logs all SQL queries executed by the application, which is invaluable for database optimization:</p><ul><li>Full SQL query</li><li>Associated parameters</li><li>Execution time</li><li>Ability to sort by execution time (identifying slow queries)</li></ul><pre>// Example query that will be recorded by Telescope<br>$users = DB::table(&#39;users&#39;)<br>    -&gt;where(&#39;active&#39;, true)<br>    -&gt;orderBy(&#39;created_at&#39;, &#39;desc&#39;)<br>    -&gt;get();</pre><h3>3. Exception Monitoring</h3><p>Telescope automatically saves all exceptions that occurred in the application, along with:</p><ul><li>Exception type</li><li>Full stack trace</li><li>File and line where the error occurred</li><li>Context (request, session)</li></ul><h3>4. Cache Operations Monitoring</h3><p>You can track all cache-related operations:</p><ul><li>Get/set/forget operations</li><li>Cache duration</li><li>Values stored in cache</li></ul><pre>// Telescope will record these operations<br>Cache::put(&#39;user_profile&#39;, $userProfile, 3600);<br>$profile = Cache::get(&#39;user_profile&#39;);</pre><h3>5. Queue Job Monitoring</h3><p>Telescope records all dispatched and executed queue jobs:</p><ul><li>Job name</li><li>Payload (data)</li><li>Time in queue</li><li>Execution time</li><li>Status (completed, failed)</li></ul><pre>// Example of a queue job monitored by Telescope<br>ProcessPodcast::dispatch($podcast)-&gt;onQueue(&#39;podcasts&#39;);</pre><h3>6. Log Monitoring</h3><p>All application log entries are also recorded by Telescope:</p><ul><li>Log level (info, warning, error, etc.)</li><li>Message</li><li>Context</li></ul><pre>// This log will be recorded by Telescope<br>Log::info(&#39;User logged in&#39;, [&#39;user_id&#39; =&gt; $user-&gt;id]);</pre><h3>7. Notification Monitoring</h3><p>Monitors sent notifications:</p><ul><li>Notification type</li><li>Recipient</li><li>Channel (mail, SMS, slack, etc.)</li><li>Delivery status</li></ul><h3>8. Event Monitoring</h3><p>Telescope tracks all events triggered in the application:</p><ul><li>Event name</li><li>Payload</li><li>Listeners</li></ul><pre>// This event will be recorded by Telescope<br>event(new UserRegistered($user));</pre><h3>9. Eloquent Model and Collection Monitoring</h3><p>Telescope can track operations performed on Eloquent models and collections:</p><ul><li>Model hydration operations</li><li>Serialization</li><li>Collection operations</li></ul><h3>10. Artisan Command Monitoring</h3><p>Records all executed Artisan commands:</p><ul><li>Command name</li><li>Parameters</li><li>Options</li><li>Execution time</li><li>Result</li></ul><h3>Practical Use Cases for Laravel Telescope</h3><h3>Debugging Application Delays</h3><p>Telescope can help identify slow SQL queries or time-consuming operations:</p><ol><li>Go to the “Requests” section in the Telescope panel</li><li>Sort requests by duration</li><li>Identify the slowest requests</li><li>Analyze associated SQL queries and other operations</li></ol><h3>Tracking Errors in Queues</h3><p>When queue jobs aren’t working properly:</p><ol><li>Go to the “Jobs” section in Telescope</li><li>Check jobs that have failed</li><li>Analyze error details, payload, and context</li></ol><h3>Diagnosing Cache Issues</h3><p>When the cache system isn’t working as expected:</p><ol><li>Go to the “Cache” section in Telescope</li><li>Review cache operations</li><li>Check if values are being properly stored and retrieved</li></ol><h3>Deployment Monitoring</h3><p>Telescope can be used to monitor applications after deployment:</p><ol><li>Temporarily enable Telescope in the production environment with appropriate security measures</li><li>Monitor logs, exceptions, and other metrics after deployment</li><li>Disable Telescope after monitoring is complete</li></ol><h3>Advanced Techniques for Using Telescope</h3><h3>1. Selective Data Recording</h3><p>You can configure which data is recorded by Telescope to reduce overhead:</p><pre>// In config/telescope.php<br>&#39;watchers&#39; =&gt; [<br>    Watchers\QueryWatcher::class =&gt; [<br>        &#39;enabled&#39; =&gt; env(&#39;TELESCOPE_QUERY_WATCHER&#39;, true),<br>        &#39;slow&#39; =&gt; 100, // Only record queries taking longer than 100ms<br>    ],<br><br>    Watchers\JobWatcher::class =&gt; [<br>        &#39;enabled&#39; =&gt; env(&#39;TELESCOPE_JOB_WATCHER&#39;, true),<br>        &#39;timeout&#39; =&gt; 60, // Only record jobs taking longer than 60s<br>    ],<br><br>    // Disable some watchers<br>    Watchers\EventWatcher::class =&gt; [<br>        &#39;enabled&#39; =&gt; false,<br>    ],<br>    // etc.<br>],</pre><h3>2. Tagging Records</h3><p>Telescope allows tagging records, which facilitates filtering and searching:</p><pre>use Laravel\Telescope\Telescope;<br><br>// Add custom tags to all recorded events<br>Telescope::tag(function ($entry) {<br>    if ($entry-&gt;type === &#39;request&#39;) {<br>        return [&#39;api&#39;, &#39;endpoint:&#39;.$entry-&gt;content[&#39;uri&#39;]];<br>    }<br>    return [];<br>});</pre><h3>3. Recording Custom Data</h3><p>You can record your own events in Telescope:</p><pre>use Laravel\Telescope\Telescope;<br><br>// Recording custom events<br>Telescope::recordCustom(&#39;custom-type&#39;, [<br>    &#39;user_id&#39; =&gt; $user-&gt;id,<br>    &#39;action&#39; =&gt; &#39;imported_data&#39;,<br>    &#39;records_count&#39; =&gt; $count,<br>    &#39;processing_time&#39; =&gt; $time,<br>]);</pre><h3>4. Data Pruning Control</h3><p>By default, Telescope stores data for 24 hours, but you can change this:</p><pre>// In config/telescope.php<br>&#39;storage&#39; =&gt; [<br>    &#39;database&#39; =&gt; [<br>        &#39;connection&#39; =&gt; env(&#39;DB_CONNECTION&#39;, &#39;mysql&#39;),<br>        &#39;chunk&#39; =&gt; 1000,<br>    ],<br>],<br><br>// Store data for 7 days<br>&#39;hours&#39; =&gt; 24 * 7,<br>// Or use a custom storage strategy<br>&#39;pruning&#39; =&gt; [<br>    &#39;enabled&#39; =&gt; true,<br>    &#39;strategy&#39; =&gt; \App\TelescopePruneStrategy::class,<br>],</pre><p>And the implementation of a custom strategy:</p><pre>namespace App;<br><br>use Illuminate\Database\Eloquent\Builder;<br>use Laravel\Telescope\Contracts\PrunesEntries;<br>use Laravel\Telescope\EntryType;<br>use Laravel\Telescope\Storage\EntryModel;<br>class TelescopePruneStrategy implements PrunesEntries<br>{<br>    /**<br>     * Prune all of the entries older than the given date.<br>     *<br>     * @param  \DateTime  $before<br>     * @return int<br>     */<br>    public function prune($before)<br>    {<br>        // Store errors longer than other records<br>        $errorsPruneCount = EntryModel::where(&#39;type&#39;, EntryType::EXCEPTION)<br>                           -&gt;where(&#39;created_at&#39;, &#39;&lt;&#39;, $before-&gt;copy()-&gt;subDays(30))<br>                           -&gt;delete();<br>        // Standard pruning for other records<br>        $normalPruneCount = EntryModel::where(&#39;type&#39;, &#39;!=&#39;, EntryType::EXCEPTION)<br>                           -&gt;where(&#39;created_at&#39;, &#39;&lt;&#39;, $before)<br>                           -&gt;delete();<br>        return $errorsPruneCount + $normalPruneCount;<br>    }<br>}</pre><h3>Telescope vs Laravel Debugbar — When to Use What</h3><h3>Laravel Telescope</h3><ul><li>When you need historical data analysis</li><li>For debugging background tasks and queues</li><li>For debugging issues that aren’t easy to reproduce</li><li>For monitoring applications over a longer time period</li></ul><h3>Laravel Debugbar</h3><ul><li>For quick real-time analysis</li><li>For frontend work and quick iteration</li><li>When you need immediate feedback</li><li>For debugging the performance of individual requests</li></ul><h3>Security and Performance</h3><h3>Security</h3><p>Telescope stores sensitive data such as SQL queries, user information, and error results. Therefore, it’s important to:</p><ol><li>Limit access to the Telescope panel only to trusted developers</li><li>Disable Telescope in production environment or strictly control access</li><li>Regularly clean old Telescope data (automatic pruning)</li></ol><h3>Performance Impact</h3><p>Telescope impacts application performance due to additional data logging operations:</p><ol><li>In production, it’s recommended to disable Telescope or enable it only temporarily for diagnosing issues</li><li>Selectively enable only the watchers you need</li><li>Consider increasing the time limit for slow queries and jobs to record only problematic operations</li></ol><h3>Advanced Implementation Techniques</h3><p>After installing Telescope as described in the Installation section above, you can further enhance its functionality with the following techniques:</p><h3>1. Fine-tuning Watcher Configuration</h3><p>Modify the config/telescope.php file to optimize performance:</p><pre>&lt;?php<br><br>return [<br>    // Enable only needed watchers<br>    &#39;watchers&#39; =&gt; [<br>        Watchers\QueryWatcher::class =&gt; [<br>            &#39;enabled&#39; =&gt; env(&#39;TELESCOPE_QUERY_WATCHER&#39;, true),<br>            &#39;slow&#39; =&gt; 50, // 50ms<br>        ],<br>        Watchers\ExceptionWatcher::class =&gt; [<br>            &#39;enabled&#39; =&gt; env(&#39;TELESCOPE_EXCEPTION_WATCHER&#39;, true),<br>        ],<br>        Watchers\LogWatcher::class =&gt; [<br>            &#39;enabled&#39; =&gt; env(&#39;TELESCOPE_LOG_WATCHER&#39;, true),<br>        ],<br>        Watchers\JobWatcher::class =&gt; [<br>            &#39;enabled&#39; =&gt; env(&#39;TELESCOPE_JOB_WATCHER&#39;, true),<br>        ],<br>        // Disable rarely used watchers<br>        Watchers\EventWatcher::class =&gt; [<br>            &#39;enabled&#39; =&gt; false,<br>        ],<br>        Watchers\ViewWatcher::class =&gt; [<br>            &#39;enabled&#39; =&gt; false,<br>        ],<br>        // etc.<br>    ],<br>    // Store data for 3 days<br>    &#39;hours&#39; =&gt; 24 * 3,<br>];</pre><h3>2. Setting Up Environment Variables</h3><p>Configure environment-specific settings:</p><p>In the .env file:</p><pre>TELESCOPE_ENABLED=true<br>TELESCOPE_QUERY_WATCHER=true<br>TELESCOPE_EXCEPTION_WATCHER=true<br>TELESCOPE_LOG_WATCHER=true<br>TELESCOPE_JOB_WATCHER=true</pre><p>In the .env.production file:</p><pre>TELESCOPE_ENABLED=false</pre><h3>3. Automating Data Pruning</h3><p>Keep your Telescope data manageable:</p><pre>php artisan telescope:prune</pre><p>Or add a scheduled task in app/Console/Kernel.php:</p><pre>/**<br> * Define the application&#39;s command schedule.<br> *<br> * @param  \Illuminate\Console\Scheduling\Schedule  $schedule<br> * @return void<br> */<br>protected function schedule(Schedule $schedule)<br>{<br>    // Daily Telescope data pruning<br>    $schedule-&gt;command(&#39;telescope:prune&#39;)-&gt;daily();<br>}</pre><h3>4. Implementing Custom Tags for Records</h3><p>Add tags to Telescope records to facilitate filtering:</p><pre>// In app/Providers/TelescopeServiceProvider.php<br>/**<br> * Register the Telescope tagger.<br> *<br> * @return void<br> */<br>protected function tags()<br>{<br>    Telescope::tag(function ($entry) {<br>        // Adding a tag with the username<br>        if ($this-&gt;app-&gt;environment(&#39;local&#39;) &amp;&amp; isset($entry-&gt;content[&#39;user_id&#39;])) {<br>            $user = \App\Models\User::find($entry-&gt;content[&#39;user_id&#39;]);<br>            if ($user) {<br>                return [&#39;user:&#39;.$user-&gt;email];<br>            }<br>        }<br><br>        // Tagging API requests<br>        if ($entry-&gt;type === &#39;request&#39; &amp;&amp; Str::startsWith($entry-&gt;content[&#39;uri&#39;], &#39;api/&#39;)) {<br>            return [&#39;api&#39;];<br>        }<br><br>        return [];<br>    });<br>}</pre><h3>5. Setting Up Custom Monitoring</h3><p>Record your own events in your code:</p><pre>use Laravel\Telescope\Telescope;<br><br>class ImportService <br>{<br>    public function importData($source)<br>    {<br>        $startTime = microtime(true);<br><br>        // Import process<br>        $count = $this-&gt;processImport($source);<br>        $endTime = microtime(true);<br>        $executionTime = $endTime - $startTime;<br><br>        // Record custom metrics in Telescope<br>        Telescope::recordCustom(&#39;data-import&#39;, [<br>            &#39;source&#39; =&gt; $source-&gt;name,<br>            &#39;records_imported&#39; =&gt; $count,<br>            &#39;execution_time&#39; =&gt; round($executionTime, 2),<br>            &#39;memory_usage&#39; =&gt; memory_get_peak_usage(true) / 1024 / 1024 . &#39; MB&#39;<br>        ]);<br><br>        return $count;<br>    }<br>}</pre><h3>Practical Use Cases</h3><h3>Scenario 1: Debugging Queue Job Issues</h3><p>Consider a case where queue jobs are being processed, but some of them fail without an obvious reason in the logs.</p><pre>// A job that sometimes fails<br>namespace App\Jobs;<br><br>use Illuminate\Bus\Queueable;<br>use Illuminate\Contracts\Queue\ShouldQueue;<br>use Illuminate\Foundation\Bus\Dispatchable;<br>use Illuminate\Queue\InteractsWithQueue;<br>use Illuminate\Queue\SerializesModels;<br><br>class ProcessSubscription implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;<br><br>    protected $subscription;<br><br>    public function __construct($subscription)<br>    {<br>        $this-&gt;subscription = $subscription;<br>    }<br><br>    public function handle()<br>    {<br>        // Complex subscription processing logic<br>        // ...<br>        // Sometimes fails at this stage<br>        $this-&gt;subscription-&gt;processPayment();<br>        // ...<br>    }<br>}</pre><p>With Laravel Telescope, you can:</p><ol><li>Go to the “Jobs” section and filter by failures</li><li>See the exact exception that caused the failure</li><li>Analyze the payload of the failed job</li><li>Check if there are any patterns among failures (e.g., only specific users)</li></ol><h3>Scenario 2: Identifying Performance Issues</h3><p>When an application is running slowly, Telescope can help identify the cause:</p><ol><li>Go to the “Requests” section and sort by duration</li><li>Identify the slowest requests</li><li>For each slow request, analyze:</li></ol><ul><li>SQL queries (number, complexity, execution time)</li><li>Cache operations (whether data is properly cached)</li><li>View loading time</li></ul><pre>// Example optimization after analysis in Telescope<br>// Before optimization<br>public function index()<br>{<br>    $posts = Post::with(&#39;comments&#39;)-&gt;get();<br>    return view(&#39;posts.index&#39;, compact(&#39;posts&#39;));<br>}<br><br>// After optimization (after identifying the problem in Telescope)<br>public function index()<br>{<br>    // Limit the amount of data retrieved<br>    $posts = Post::with([&#39;comments&#39; =&gt; function($query) {<br>        $query-&gt;latest()-&gt;limit(5);<br>    }])-&gt;paginate(20);<br>    // Cache results<br>    $posts = Cache::remember(&#39;homepage.posts&#39;, 3600, function() use ($posts) {<br>        return $posts;<br>    });<br><br>    return view(&#39;posts.index&#39;, compact(&#39;posts&#39;));<br>}</pre><h3>Scenario 3: Diagnosing API Validation Errors</h3><p>Imagine an API that sometimes returns validation errors that are difficult to diagnose:</p><pre>// API Controller<br>public function store(StoreProductRequest $request)<br>{<br>    // Validation in StoreProductRequest class<br>    $product = Product::create($request-&gt;validated());<br>    return response()-&gt;json($product, 201);<br>}</pre><p>With Laravel Telescope, you can:</p><ol><li>Go to the “Requests” section and filter by requests with response code 422 (validation error)</li><li>See the exact input data that caused the error</li><li>Analyze the validation rules that weren’t met</li><li>Identify patterns in failed requests</li></ol><h3>Conclusion</h3><p>Laravel Telescope is a powerful tool that significantly improves the process of debugging and monitoring Laravel applications. The main advantages include:</p><ol><li><strong>Comprehensive insight</strong> into various aspects of application operation</li><li><strong>Operation history</strong> that allows for analysis of problems after they occur</li><li><strong>Ease of implementation</strong> thanks to integration with the Laravel ecosystem</li><li><strong>Configuration flexibility</strong> that allows the tool to be adapted to project needs</li></ol><p>Telescope works best as a development tool, although with proper security configuration, it can also be used for temporary monitoring of production environments when diagnosing difficult issues.</p><p>Remember to always be aware of Telescope’s impact on application performance and properly manage security access to the admin panel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a3b47a3e7c4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/laravel-telescope-advanced-debugging-and-monitoring-for-laravel-applications-4a3b47a3e7c4">Laravel Telescope — Advanced Debugging and Monitoring for Laravel Applications</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Debugbar — Advanced Application Debugging Capabilities]]></title>
            <link>https://levelup.gitconnected.com/laravel-debugbar-advanced-application-debugging-capabilities-c4f31845c3d3?source=rss-be410870b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f31845c3d3</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dominik]]></dc:creator>
            <pubDate>Thu, 15 May 2025 11:02:20 GMT</pubDate>
            <atom:updated>2025-05-20T11:56:21.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*973WcRjz9WkGLLZig_QOiA.png" /></figure><h3>Laravel Debugbar — Advanced Application Debugging Capabilities</h3><h3>Introduction</h3><p>Debugging is an integral part of every developer’s work. In the Laravel ecosystem, one of the most powerful tools for this purpose is <strong>Laravel Debugbar</strong>, created by Barry vd. Heuvel. Unlike standard functions like dd() or dump() that halt script execution, Debugbar allows continuous monitoring of your application during runtime.</p><p>In this article, you’ll discover advanced features of Laravel Debugbar that will significantly speed up your debugging process and help you better understand what’s happening in your Laravel application.</p><h3>Table of Contents</h3><ol><li>Installation and Configuration</li><li>Non-invasive Debugging with Debugbar::addMessage()</li><li>Performance Measurement with Debugbar::startMeasure()</li><li>SQL Query Tracking</li><li>API and Ajax Debugging</li><li>Custom Data Collections</li><li>Debugging in Tests</li><li>Practical Examples</li><li>Summary</li></ol><h3>Installation and Configuration</h3><p>Let’s start with the basics. To install Laravel Debugbar, run the following command:</p><pre>composer require barryvdh/laravel-debugbar --dev</pre><p>Then publish the configuration file:</p><pre>php artisan vendor:publish --provider=&quot;Barryvdh\Debugbar\ServiceProvider&quot;</pre><p>By default, Debugbar is enabled in the local environment and disabled in production. You can modify this in the config/debugbar.php configuration file.</p><h3>Non-invasive Debugging with Debugbar::addMessage()</h3><p>One of the biggest advantages of Debugbar over standard debugging methods is the ability to add messages without halting script execution. Let’s look at an example:</p><pre>use Debugbar;<br><br>public function show($id)<br>{<br>    $user = User::find($id);<br>    // Instead of dd($user) or dump($user)<br>    Debugbar::info($user);<br>    // We can also add custom messages<br>    Debugbar::addMessage(&#39;User has been retrieved&#39;, &#39;info&#39;);<br>    // Note that the application continues running<br>    return view(&#39;users.show&#39;, compact(&#39;user&#39;));<br>}</pre><p>Debugbar offers various message types that are color-coded in the interface:</p><pre>Debugbar::info($variable);      // Information<br>Debugbar::error($variable);     // Error<br>Debugbar::warning($variable);   // Warning<br>Debugbar::addMessage($variable, &#39;debug&#39;); // Debug</pre><p>Moreover, you can log complex data structures like arrays, collections, or objects:</p><pre>$users = User::with(&#39;posts&#39;)-&gt;get();<br>Debugbar::info($users);</pre><p>Debugbar automatically formats the data in a readable way, allowing you to expand nested structures.</p><h3>Performance Measurement with Debugbar::startMeasure()</h3><p>One of the less known but highly useful tools in Debugbar is the ability to measure execution time of specific code blocks:</p><pre>Debugbar::startMeasure(&#39;render&#39;, &#39;View rendering time&#39;);<br><br>// Some complex code we want to measure<br>$view = view(&#39;complex.view&#39;, $data)-&gt;render();<br>Debugbar::stopMeasure(&#39;render&#39;);</pre><p>You can nest measurements to precisely locate slow code segments:</p><pre>Debugbar::startMeasure(&#39;total&#39;, &#39;Total processing time&#39;);<br>Debugbar::startMeasure(&#39;database&#39;, &#39;Database operations&#39;);<br><br>$posts = Post::with(&#39;comments&#39;, &#39;author&#39;, &#39;categories&#39;)-&gt;get();<br><br>Debugbar::stopMeasure(&#39;database&#39;);<br>Debugbar::startMeasure(&#39;transform&#39;, &#39;Data transformation&#39;);<br><br>$transformedData = $this-&gt;transformService-&gt;transformPosts($posts);<br><br>Debugbar::stopMeasure(&#39;transform&#39;);<br>Debugbar::startMeasure(&#39;render&#39;, &#39;View rendering&#39;);<br><br>$view = view(&#39;posts.index&#39;, compact(&#39;transformedData&#39;))-&gt;render();<br><br>Debugbar::stopMeasure(&#39;render&#39;);<br>Debugbar::stopMeasure(&#39;total&#39;);<br><br>return $view;</pre><p>This is particularly useful for application optimization, allowing you to precisely identify bottlenecks.</p><h3>SQL Query Tracking</h3><p>Laravel Debugbar automatically tracks all SQL queries executed during request processing. However, you can add your own comments to queries for easier identification:</p><pre>DB::enableQueryLog();<br><br>// Add a comment to the next query<br>Debugbar::addMessage(&#39;Fetching active users&#39;, &#39;queries&#39;);<br><br>$activeUsers = User::where(&#39;status&#39;, &#39;active&#39;)-&gt;get();<br><br>// Manually add query to Debugbar<br>Debugbar::addMessage(DB::getQueryLog(), &#39;queries&#39;);</pre><p>Debugbar shows not only the queries themselves but also their execution time, parameters, and the location in code from where they were called.</p><h3>API and Ajax Debugging</h3><p>Debugbar works by default only for HTML responses. However, you can enable it for Ajax and API requests:</p><pre>// In config/debugbar.php configuration file:<br>&#39;capture_ajax&#39; =&gt; true,</pre><p>For API requests, you can use a special method:</p><pre>public function apiEndpoint()<br>{<br>    $data = $this-&gt;processData();<br><br>    // API logging<br>    Debugbar::debug(&#39;API called with parameters: &#39; . json_encode(request()-&gt;all()));<br>    <br>    // Add data to a separate tab in Debugbar<br>    Debugbar::addCollector(new GenericCollector(&#39;api_data&#39;, $data));<br><br>    return response()-&gt;json($data);<br>}</pre><p>Laravel Debugbar also offers a special JavaScript client that can be used to debug Ajax requests:</p><pre>// In JavaScript file<br>$.ajax({<br>    url: &#39;/api/data&#39;,<br>    success: function(data) {<br>        // Debug response<br>        LaravelDebugbar.info(&#39;Ajax response&#39;, data);<br>    }<br>});</pre><h3>Custom Data Collections</h3><p>One of the most advanced features of Debugbar is the ability to create custom data collectors. You can create your own tab in the Debugbar interface to track data that interests you:</p><pre>use DebugBar\DataCollector\DataCollector;<br>use DebugBar\DataCollector\Renderable;<br><br>class MyCustomCollector extends DataCollector implements Renderable<br>{<br>    protected $data = [];<br><br>    public function addData($key, $value)<br>    {<br>        $this-&gt;data[$key] = $value;<br>    }<br><br>    public function collect()<br>    {<br>        return $this-&gt;data;<br>    }<br><br>    public function getName()<br>    {<br>        return &#39;custom&#39;;<br>    }<br><br>    public function getWidgets()<br>    {<br>        return [<br>            &quot;custom&quot; =&gt; [<br>                &quot;icon&quot; =&gt; &quot;cubes&quot;,<br>                &quot;widget&quot; =&gt; &quot;PhpDebugBar.Widgets.VariableListWidget&quot;,<br>                &quot;map&quot; =&gt; &quot;custom&quot;,<br>                &quot;default&quot; =&gt; &quot;{}&quot;<br>            ]<br>        ];<br>    }<br>}<br><br>// Register collector<br>$customCollector = new MyCustomCollector();<br>Debugbar::addCollector($customCollector);<br><br>// Add data<br>$customCollector-&gt;addData(&#39;key1&#39;, &#39;value1&#39;);<br>$customCollector-&gt;addData(&#39;key2&#39;, [&#39;nested&#39; =&gt; &#39;array&#39;]);</pre><p>This allows you to create specialized debugging tools for your application’s specific needs.</p><h3>Debugging in Tests</h3><p>Laravel Debugbar can also be used in tests, which is particularly useful when debugging slow-running tests:</p><pre>public function testSlowOperation()<br>{<br>    Debugbar::enable(); // Enable Debugbar in this test<br>    Debugbar::startMeasure(&#39;slow_test&#39;, &#39;Slow test&#39;);<br>    <br>    // Test code<br>    $result = $this-&gt;service-&gt;performComplexOperation();<br>    Debugbar::stopMeasure(&#39;slow_test&#39;);<br>    <br>    // Save debug report to file<br>    $debugbarData = Debugbar::getData();<br>    <br>    file_put_contents(<br>        storage_path(&#39;logs/test_debug_&#39; . time() . &#39;.json&#39;),<br>        json_encode($debugbarData)<br>    );<br><br>    $this-&gt;assertTrue($result);<br>}</pre><p>You can then analyze the saved data to identify slow code segments.</p><h3>Practical Examples</h3><h3>Example 1: Debugging N+1 Query Problems</h3><pre>public function index()<br>{<br>    Debugbar::startMeasure(&#39;posts_query&#39;, &#39;Fetching posts&#39;);<br><br>    // N+1 query problem<br>    $posts = Post::all();<br>    Debugbar::info(&#39;Number of posts: &#39; . count($posts));<br>    Debugbar::stopMeasure(&#39;posts_query&#39;);<br>    <br>    foreach ($posts as $post) {<br>        // Each of these calls will generate an additional query - Debugbar will show them all<br>        $post-&gt;author-&gt;name;<br>    }<br>    <br>    // Solution<br>    Debugbar::startMeasure(&#39;posts_eager&#39;, &#39;Fetching posts with eager loading&#39;);<br>    $optimizedPosts = Post::with(&#39;author&#39;)-&gt;get();<br>    <br>    Debugbar::stopMeasure(&#39;posts_eager&#39;);<br>    <br>    return view(&#39;posts.index&#39;, compact(&#39;optimizedPosts&#39;));<br>}</pre><h3>Example 2: Memory Usage Debugging</h3><pre>public function processLargeDataset()<br>{<br>    Debugbar::startMeasure(&#39;memory_test&#39;, &#39;Memory usage test&#39;);<br>    $initialMemory = memory_get_usage();<br>    Debugbar::info(&#39;Initial memory usage: &#39; . $this-&gt;formatBytes($initialMemory));<br>    <br>    // Memory-intensive operation<br>    $data = $this-&gt;largeDataService-&gt;processData();<br>    $afterMemory = memory_get_usage();<br>    <br>    Debugbar::info(&#39;Final memory usage: &#39; . $this-&gt;formatBytes($afterMemory));<br>    Debugbar::info(&#39;Difference: &#39; . $this-&gt;formatBytes($afterMemory - $initialMemory));<br>    Debugbar::stopMeasure(&#39;memory_test&#39;);<br>    <br>    return response()-&gt;json([&#39;status&#39; =&gt; &#39;completed&#39;]);<br>}<br><br>private function formatBytes($bytes, $precision = 2)<br>{<br>    $units = [&#39;B&#39;, &#39;KB&#39;, &#39;MB&#39;, &#39;GB&#39;, &#39;TB&#39;];<br>    $bytes = max($bytes, 0);<br>    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));<br>    $pow = min($pow, count($units) - 1);<br>    $bytes /= (1 &lt;&lt; (10 * $pow));<br><br>    return round($bytes, $precision) . &#39; &#39; . $units[$pow];<br>}</pre><h3>Example 3: Debugging Multi-threaded Processes</h3><pre>public function runQueue()<br>{<br>    Debugbar::startMeasure(&#39;queue_process&#39;, &#39;Queue processing&#39;);<br><br>    dispatch(function () {<br>        // This won&#39;t be visible in Debugbar as it runs in a different process<br>        logger(&#39;Job started&#39;);<br>    });<br>    <br>    // Solution: save job ID and monitor its status<br>    $jobId = Str::uuid();<br>    Debugbar::info(&#39;Job with ID: &#39; . $jobId . &#39; has been queued&#39;);<br><br>    dispatch(function () use ($jobId) {<br>        cache()-&gt;put(&#39;job_status_&#39; . $jobId, &#39;running&#39;, now()-&gt;addMinutes(5));<br>        // Processing<br>        cache()-&gt;put(&#39;job_status_&#39; . $jobId, &#39;completed&#39;, now()-&gt;addMinutes(5));<br>    });<br><br>    // In a real application, we would use AJAX to check status<br>    Debugbar::info(&#39;Job status can be checked via cache()-&gt;get(&quot;job_status_&#39; . $jobId . &#39;&quot;)&#39;);<br>    Debugbar::stopMeasure(&#39;queue_process&#39;);<br><br>    return response()-&gt;json([&#39;job_id&#39; =&gt; $jobId]);<br>}</pre><h3>Summary</h3><p>Laravel Debugbar is an incredibly powerful tool that goes far beyond basic debugging functions like dump() or dd(). Its main advantages are:</p><ol><li><strong>Non-invasive debugging</strong> — ability to add messages and track data without stopping application execution</li><li><strong>Advanced performance profiling</strong> — precise timing measurements of specific code segments</li><li><strong>Full SQL query visibility</strong> — automatic tracking of all queries with execution time and parameters</li><li><strong>Extensibility</strong> — ability to create custom data collectors</li><li><strong>AJAX and API support</strong> — debugging capabilities in non-standard response environments</li></ol><p>Implementing Laravel Debugbar in your development process will significantly speed up problem identification and resolution in your application. Most importantly, it allows you to observe application behavior during actual runtime, not just during static code analysis.</p><p>Remember to always disable Debugbar in production environment, as it can affect application performance and expose sensitive information.</p><p>If you found this article helpful, consider following me on <a href="https://www.linkedin.com/in/dominik-jasi%C5%84ski/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f31845c3d3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/laravel-debugbar-advanced-application-debugging-capabilities-c4f31845c3d3">Laravel Debugbar — Advanced Application Debugging Capabilities</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>