<?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"><channel><title><![CDATA[Raja Dev Solutions]]></title><description><![CDATA[Raja Dev Solutions]]></description><link>https://rajadevsolutions.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 24 Nov 2026 11:41:33 GMT</lastBuildDate><atom:link href="https://rajadevsolutions.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Why Your fetch() Call Silently Fails: The 404 Trap and How to Fix It]]></title><description><![CDATA[You call fetch(), you get a response, you read the JSON — and your page shows nothing. No error in the console, no red text, nothing. The request "worked"…]]></description><link>https://rajadevsolutions.hashnode.dev/why-your-fetch-call-silently-fails-the-404-trap-and-how-to-fix-it</link><guid isPermaLink="true">https://rajadevsolutions.hashnode.dev/why-your-fetch-call-silently-fails-the-404-trap-and-how-to-fix-it</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[fetch API]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Raja Hunain]]></dc:creator><pubDate>Tue, 24 Nov 2026 07:32:31 GMT</pubDate><content:encoded><![CDATA[<p>You call <code>fetch()</code>, you get a response, you read the JSON — and your page shows nothing. No error in the console, no red text, nothing. The request "worked". Except it didn't.</p>
<p>This is the single most confusing thing about the Fetch API, and it catches almost everyone the first time.</p>
<h2>fetch() does not throw for a 404</h2>
<p>Here is the mental model most beginners have: request fails → promise rejects → catch runs. That is how Axios works. It is not how <code>fetch()</code> works.</p>
<p><code>fetch()</code> only rejects when the request could not be made at all: no internet, a DNS failure, a blocked request. An HTTP error like 404 or 500 still <strong>resolves</strong> with a Response object. So this code fails silently:</p>
<pre><code class="language-js">const response = await fetch('https://jsonplaceholder.typicode.com/users/9999');
const user = await response.json();
console.log(user.name); // undefined — not an error
</code></pre>
<p>The server answered 404. Your code carried on as if everything was fine, and the bug surfaced three functions later as <code>undefined</code> — far away from the real cause.</p>
<h2>The one check that fixes it</h2>
<p><code>response.ok</code> is <code>true</code> only for status codes 200–299. Check it before you read the body, and throw your own error:</p>
<pre><code class="language-js">async function getUser(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);

  if (!response.ok) {
    throw new Error(`HTTP ${response.status} ${response.statusText}`);
  }

  return response.json();
}

try {
  const user = await getUser(9999);
  console.log(user.name);
} catch (error) {
  console.error('Could not load user:', error.message);
  // Could not load user: HTTP 404 Not Found
}
</code></pre>
<p>Now the failure is loud, local, and debuggable. Build this check into one small helper and reuse it everywhere — a <code>request()</code> function that checks the status, parses the JSON, and adds a timeout with <code>AbortSignal.timeout()</code>. Every call site then stays one line long.</p>
<h2>Two friends of the same trap</h2>
<p><strong>CORS errors</strong> look like fetch failures but are not your code's fault: the browser blocks a cross-origin request unless the server sends the right header. No option in your <code>fetch()</code> call can override that — it is a server setting.</p>
<p><strong>Empty responses</strong> are the same story in reverse: calling <code>.json()</code> on a 204 No Content response throws a <code>SyntaxError</code>. Check the <code>Content-Type</code> header first, or fall back to <code>.text()</code>.</p>
<h2>The habit to keep</h2>
<p><code>fetch()</code> is a low-level tool — it hands you the raw response and trusts you to inspect it. The habit is simple: never read a body before checking <code>response.ok</code>. Do that, and the "silent failure" class of bugs disappears from your code entirely.</p>
<p>I wrote a complete step-by-step tutorial on calling REST APIs with the Fetch API — GET, POST, auth headers, timeouts, and parallel requests with working code — here: <a href="https://rajadevsolutions.online/blog/how-to-use-javascript-fetch-api-to-call-a-rest-api">https://rajadevsolutions.online/blog/how-to-use-javascript-fetch-api-to-call-a-rest-api</a></p>
<p>Every example runs against a free practice API, so you can try it in your browser console today.</p>
]]></content:encoded></item><item><title><![CDATA[Why Raising max_execution_time Didn't Fix Your PHP Error]]></title><description><![CDATA[You raised max_execution_time from 30 to 300 seconds, deployed, clicked the button again — and the same error came back. If that sounds familiar, the PHP…]]></description><link>https://rajadevsolutions.hashnode.dev/why-raising-max-execution-time-didn-t-fix-your-php-error</link><guid isPermaLink="true">https://rajadevsolutions.hashnode.dev/why-raising-max-execution-time-didn-t-fix-your-php-error</guid><category><![CDATA[PHP]]></category><category><![CDATA[debugging]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Raja Hunain]]></dc:creator><pubDate>Mon, 23 Nov 2026 14:42:15 GMT</pubDate><content:encoded><![CDATA[<p>You raised <code>max_execution_time</code> from 30 to 300 seconds, deployed, clicked the button again — and the same error came back. If that sounds familiar, the PHP time limit was never your problem. It was just the first suspect.</p>
<p>Here is the mistake: a PHP request does not have one timeout. It has a stack of them, and the shortest one wins. Until you find out which clock actually stopped the request, every fix is a guess.</p>
<h2>The limit that lies to you</h2>
<p>On Linux, <code>max_execution_time</code> only counts the time PHP itself spends running code. Waiting does not count — not a slow database query, not a hanging API call, not <code>sleep()</code>. So when a script dies at exactly 30 seconds, it did 30 seconds of actual PHP work. That points at a loop that never ends, or a request doing far too much at once — not at a limit that is too low.</p>
<p>And the line number in the error message is where PHP happened to be when the timer expired, not where the slowness lives. A loop running a million times gets reported on whatever line it was executing at second 30.</p>
<h2>The other clocks</h2>
<p>Match what you saw, and you will know where to look:</p>
<ul>
<li><strong>PHP fatal at exactly the limit</strong> — PHP stopped it. Check the PHP or Laravel log.</li>
<li><strong>504 Gateway Time-out, often at exactly 60 seconds</strong> — nginx stopped waiting. The nginx error log says <code>upstream timed out</code>, and the fix is <code>fastcgi_read_timeout</code>, not <code>php.ini</code>.</li>
<li><strong>502 Bad Gateway</strong> — PHP-FPM killed the worker. The FPM log says <code>execution timed out</code>, and the pool setting <code>request_terminate_timeout</code> is the cause.</li>
<li><strong>Queue job failed, worker exit code 137</strong> — the Laravel worker's <code>--timeout</code> killed it.</li>
</ul>
<h2>Fix the work, then the limit</h2>
<p>The durable fix is almost always in the code. Close the runaway loop. Replace the N+1 query pattern with eager loading and <code>chunk()</code> so an export processes 500 rows at a time instead of loading a whole table. Move imports and bulk jobs that genuinely take minutes into a queue or a cron script, where the web time limit does not apply at all.</p>
<p>Only when the work is genuinely large should you raise the limit — narrowly, for that one script, with <code>set_time_limit(300)</code> at the top of it. Raising it for the whole site just lets the next broken script hold a worker for five minutes instead of thirty.</p>
<p>The full step-by-step guide, with the reproduction commands, the diagnosis table, and every timer set correctly, is here:</p>
<p><a href="https://rajadevsolutions.online/errors/how-to-fix-maximum-execution-time-exceeded-error-in-php">https://rajadevsolutions.online/errors/how-to-fix-maximum-execution-time-exceeded-error-in-php</a></p>
]]></content:encoded></item><item><title><![CDATA[The 3-Second MySQL Query That Was Fixed by One Composite Index]]></title><description><![CDATA[A user page in our app took three seconds to load. Not the whole app — one page, one query. The query looked harmless: Twenty rows. One user. Three…]]></description><link>https://rajadevsolutions.hashnode.dev/the-3-second-mysql-query-that-was-fixed-by-one-composite-index</link><guid isPermaLink="true">https://rajadevsolutions.hashnode.dev/the-3-second-mysql-query-that-was-fixed-by-one-composite-index</guid><category><![CDATA[MySQL]]></category><category><![CDATA[Databases]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Raja Hunain]]></dc:creator><pubDate>Mon, 23 Nov 2026 05:11:06 GMT</pubDate><content:encoded><![CDATA[<p>A user page in our app took three seconds to load. Not the whole app — one page, one query. The query looked harmless:</p>
<pre><code class="language-sql">SELECT * FROM orders
WHERE user_id = 1234
ORDER BY created_at DESC
LIMIT 20;
</code></pre>
<p>Twenty rows. One user. Three seconds. Something was wrong, and guessing would have wasted the morning, so I did the one thing that actually answers the question: I ran <code>EXPLAIN</code>.</p>
<h2>What EXPLAIN said</h2>
<pre><code class="language-sql">EXPLAIN SELECT * FROM orders WHERE user_id = 1234 ORDER BY created_at DESC LIMIT 20;
-- type=ALL  key=NULL  rows=498489  Extra=Using where; Using filesort
</code></pre>
<p>Three facts in one line. <code>type: ALL</code> — a full table scan of nearly half a million rows. <code>key: NULL</code> — no index was used. <code>Using filesort</code> — after scanning everything, MySQL sorted it all by hand. The query was not slow because the database is slow. It was slow because the database was doing roughly 25,000 times more work than the answer required.</p>
<h2>The first fix — and why it was not enough</h2>
<p>The obvious fix was an index on <code>user_id</code>:</p>
<pre><code class="language-sql">ALTER TABLE orders ADD INDEX idx_user (user_id);
-- type=ref  key=idx_user  rows=25  Extra=Using filesort
</code></pre>
<p>Rows examined fell from 498,489 to 25. A huge improvement — and still not the whole fix. <code>Using filesort</code> was still there. The index found the right rows, but they were not in the order the query asked for, so MySQL sorted 25 rows every time. Twenty-five rows is cheap to sort, but the sort was a symptom: the index did not match the query.</p>
<h2>The fix that finished it</h2>
<p>The query filters on <code>user_id</code> and sorts on <code>created_at</code>. One index that covers both, in that order:</p>
<pre><code class="language-sql">ALTER TABLE orders ADD INDEX idx_user_created (user_id, created_at);
-- type=ref  key=idx_user_created  rows=25  Extra=Backward index scan
</code></pre>
<p>The index is already ordered by <code>created_at</code> inside each <code>user_id</code>, so MySQL reads it backwards and stops after 20 rows. No scan, no sort. The page went from three seconds to milliseconds, and the total change was two index definitions — the second one replacing the need for the first.</p>
<h2>The rule I kept</h2>
<p>Put the equality columns first in a composite index, then the columns you sort or range-filter on, in the same order the query uses them. And check the plan after every change: <code>EXPLAIN</code> tells you whether the fix worked, and it tells you the truth faster than any amount of reasoning about the query.</p>
<p>I wrote the full version of this — how to find slow queries in the slow query log, how to read every <code>EXPLAIN</code> column, the function-wrapped-column trap that hides an index from MySQL, and the pagination pattern that gets slower on every page — here:</p>
<p><a href="https://rajadevsolutions.online/blog/how-to-fix-slow-mysql-queries-with-explain">https://rajadevsolutions.online/blog/how-to-fix-slow-mysql-queries-with-explain</a></p>
<p>Most slow queries are fixed by the smallest change, not the biggest.</p>
]]></content:encoded></item><item><title><![CDATA[Deploying Laravel Without SSH: The Cron Trick That Runs Your Migrations]]></title><description><![CDATA[Most Laravel deployment guides assume you have SSH. You run php artisan migrate, you run php artisan storage:link, you cache the config, and you are done…]]></description><link>https://rajadevsolutions.hashnode.dev/deploying-laravel-without-ssh-the-cron-trick-that-runs-your-migrations</link><guid isPermaLink="true">https://rajadevsolutions.hashnode.dev/deploying-laravel-without-ssh-the-cron-trick-that-runs-your-migrations</guid><category><![CDATA[Laravel]]></category><category><![CDATA[deployment]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Raja Hunain]]></dc:creator><pubDate>Sun, 22 Nov 2026 14:33:14 GMT</pubDate><content:encoded><![CDATA[<p>Most Laravel deployment guides assume you have SSH. You run <code>php artisan migrate</code>, you run <code>php artisan storage:link</code>, you cache the config, and you are done. But the cheapest shared hosting plans — the ones beginners actually buy — often have no SSH at all. You get cPanel, a File Manager, phpMyAdmin and cron jobs. No terminal.</p>
<p>That does not mean you cannot deploy Laravel. It means you run Artisan a different way: through a cron job that fires once.</p>
<h2>The problem</h2>
<p>A fresh Laravel app needs three Artisan commands before it works: migrations to build the tables, <code>storage:link</code> so uploads are reachable, and <code>config:cache</code> so the app stops re-reading <code>.env</code> on every request. Without SSH there is no place to type them. Uploading the project is easy — zip it, push it through the File Manager, extract it next to <code>public_html</code> — but an app with no tables is a 500 error waiting to happen.</p>
<h2>The trick: a one-off cron job</h2>
<p>cPanel's Cron Jobs page lets you schedule any command. So instead of a recurring schedule, you create a job that runs once, a minute from now, and then you delete it:</p>
<pre><code>cd /home/username/laravel-app &amp;&amp; /usr/bin/php artisan migrate --force
</code></pre>
<p>A minute later you open phpMyAdmin. If the tables are there, it worked. Then delete the cron job so it never runs again. The <code>--force</code> flag is not optional: Artisan refuses to run migrations in production without it, and on the server your app is in production.</p>
<p>The same trick covers the other two commands. <code>php artisan storage:link</code> through a one-off cron job creates the symlink that makes uploaded files publicly readable — without it, every upload returns 404 even though the file exists on disk. And <code>config:cache</code>, <code>route:cache</code> and <code>view:cache</code> go through the same route when you have no terminal.</p>
<h2>Three rules that keep this safe</h2>
<p>First, always delete the one-off job after it runs. A migration command sitting in cron is a loaded gun: if it ever fires again unexpectedly, it runs migrations you may not want yet.</p>
<p>Second, remember that <code>config:cache</code> freezes your configuration. After it runs, Laravel ignores <code>.env</code> completely. Every time you change a value in <code>.env</code> on the server — a password, a mail setting, anything — re-run <code>config:cache</code> through the same trick, or the app keeps using the old value and you will spend an hour debugging a setting you already fixed.</p>
<p>Third, never generate a new app key on the server. Copy the <code>APP_KEY</code> from your local <code>.env</code>. Anything encrypted with the old key stops working if you regenerate it on a live app.</p>
<h2>What about the scheduler?</h2>
<p>If your app uses scheduled tasks, this is where cron stops being a trick and becomes the real setup. Laravel's scheduler needs one permanent entry:</p>
<pre><code>* * * * * cd /home/username/laravel-app &amp;&amp; php artisan schedule:run &gt;&gt; /dev/null 2&gt;&amp;1
</code></pre>
<p>That one stays. Everything else — migrations, storage link, caches — is a one-off job you create, watch, and delete.</p>
<h2>Why this matters</h2>
<p>SSH is a convenience, not a requirement. The deployment itself is just files in the right place and three commands run once. Knowing the cron workaround means the cheapest hosting plan is no longer a reason to delay launching — and it means you can fix a live app from any computer with a browser, no terminal needed.</p>
<p>I wrote the full deployment guide this comes from — the folder layout that keeps <code>.env</code> out of the web root, the <code>.htaccess</code> rule that points the domain at <code>public/</code>, the database setup, and a table of every common deployment error with its fix — here: <a href="https://rajadevsolutions.online/blog/how-to-deploy-laravel-13-app-on-shared-hosting">https://rajadevsolutions.online/blog/how-to-deploy-laravel-13-app-on-shared-hosting</a></p>
]]></content:encoded></item><item><title><![CDATA[Why session_start() Fails After HTML — and Where Your Cookie Actually Goes]]></title><description><![CDATA[You put session_start() in the middle of your page, right where the login box is. The page loads, the session never starts, and PHP prints: No crash, no…]]></description><link>https://rajadevsolutions.hashnode.dev/why-session-start-fails-after-html-and-where-your-cookie-actually-goes</link><guid isPermaLink="true">https://rajadevsolutions.hashnode.dev/why-session-start-fails-after-html-and-where-your-cookie-actually-goes</guid><category><![CDATA[PHP]]></category><category><![CDATA[sessions]]></category><category><![CDATA[debugging]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Raja Hunain]]></dc:creator><pubDate>Sun, 22 Nov 2026 05:13:39 GMT</pubDate><content:encoded><![CDATA[<p>You put <code>session_start()</code> in the middle of your page, right where the login box is. The page loads, the session never starts, and PHP prints:</p>
<pre><code>Warning: Cannot modify header information - headers already sent
</code></pre>
<p>No crash, no stack trace — just a session that quietly does not exist. Here is what is actually happening, and the two-minute fix.</p>
<h2>Sessions live in headers, not in the page</h2>
<p>A PHP session works through a cookie. When you call <code>session_start()</code>, PHP sends a <code>Set-Cookie</code> header with the session id, and the browser sends it back on every later request. That is how the server recognises the same user twice.</p>
<p>Headers, though, must travel before the body. An HTTP response is headers first, then HTML — in that strict order. The moment your script outputs its first byte of HTML, PHP seals the headers and sends them. A <code>session_start()</code> that comes after that has nowhere to put its cookie, so PHP warns and skips it.</p>
<h2>The pattern that fails</h2>
<pre><code class="language-php">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;Login&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
&lt;?php session_start(); ?&gt;
</code></pre>
<p>By the time PHP reaches <code>session_start()</code>, the <code>&lt;!DOCTYPE html&gt;</code> line has already gone out. The session cookie is lost, <code>$_SESSION</code> stays empty, and the login that depends on it fails in a way that looks like a completely different bug.</p>
<h2>The fix: sessions first, HTML last</h2>
<pre><code class="language-php">&lt;?php
session_start();
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;Login&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
</code></pre>
<p>Move the session start to the very first line of the script, before any HTML, any echo, and any whitespace. The same rule covers <code>setcookie()</code> and every <code>header()</code> call — all header work happens before the first byte of output.</p>
<h2>The two invisible causes</h2>
<p>If the session start is already at the top and it still fails, the output is coming from somewhere you cannot see:</p>
<ul>
<li><strong>Whitespace before <code>&lt;?php</code></strong> — a blank line or a space before the opening tag is output. Make <code>&lt;?php</code> the first characters of the file.</li>
<li><strong>The UTF-8 BOM</strong> — three invisible bytes some editors add at the start of a file. Re-save the file as "UTF-8 without BOM".</li>
</ul>
<p>And check your includes. If a required file ends with <code>?&gt;</code> plus a newline, that newline is output too. Files with only PHP should have no closing tag at all.</p>
<h2>When buffering is the wrong answer</h2>
<p>You will see advice to add <code>ob_start()</code> at the top of every file. It works — output buffering holds the HTML in memory, so the session cookie still gets out. But it hides the real problem instead of fixing it, and it holds whole responses in memory. Use it for legacy templates you cannot restructure, not as a habit.</p>
<h2>Finding the exact line</h2>
<p>The warning tells you where the output started — read its first half:</p>
<pre><code>(output started at /var/www/app/login.php:2) in /var/www/app/login.php on line 9
</code></pre>
<p>Line 2 is the bug. Line 9 is only the victim. If the message is not enough, <code>headers_sent($file, $line)</code> will tell you the file and line that sent output.</p>
<p>I covered the whole error — whitespace, includes, the BOM, output buffering, and a causes table — step by step here: <a href="https://rajadevsolutions.online/errors/how-to-fix-headers-already-sent-error-in-php">How to Fix "Headers Already Sent" Error in PHP</a></p>
<p>Sessions are not magic. They are one cookie, sent in the headers, before the page. Put the session first and the page second, and the warning never comes back.</p>
]]></content:encoded></item><item><title><![CDATA[Docker + Laravel: Why Your App Can't Reach MySQL (and the One-Line Fix)]]></title><description><![CDATA[You dockerised your Laravel app, ran docker compose up, and the app answers with this: Everything worked on your host machine five minutes ago. Nothing…]]></description><link>https://rajadevsolutions.hashnode.dev/docker-laravel-why-your-app-can-t-reach-mysql-and-the-one-line-fix</link><guid isPermaLink="true">https://rajadevsolutions.hashnode.dev/docker-laravel-why-your-app-can-t-reach-mysql-and-the-one-line-fix</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Docker]]></category><category><![CDATA[MySQL]]></category><category><![CDATA[debugging]]></category><dc:creator><![CDATA[Raja Hunain]]></dc:creator><pubDate>Sat, 21 Nov 2026 14:23:59 GMT</pubDate><content:encoded><![CDATA[<p>You dockerised your Laravel app, ran <code>docker compose up</code>, and the app answers with this:</p>
<pre><code>SQLSTATE[HY000] [2002] Connection refused
</code></pre>
<p>Everything worked on your host machine five minutes ago. Nothing about the database changed. So why can Laravel suddenly not reach MySQL?</p>
<h2>The one thing to understand: localhost is not the same everywhere</h2>
<p>Inside Docker, <code>127.0.0.1</code> means <strong>this container</strong> — not your computer, and not the database container. So a Laravel container with <code>DB_HOST=127.0.0.1</code> is asking itself whether it runs MySQL. It does not, so the connection is refused. Your <code>.env</code> was correct on the host and wrong inside the container, at the same time.</p>
<p>Containers on the same Compose network reach each other by <strong>service name</strong>. With Laravel Sail, the database service is called <code>mysql</code>, so the fix is one line in your <code>.env</code>:</p>
<pre><code class="language-dotenv">DB_HOST=mysql
DB_PORT=3306
</code></pre>
<p>If your own <code>docker-compose.yml</code> names the service <code>db</code> or <code>database</code>, use that exact name instead.</p>
<h2>Run Artisan inside the container</h2>
<p>The second half of the same mistake is running commands in the wrong place. With a container-style <code>.env</code>, plain <code>php artisan migrate</code> on your host machine reads a host that only makes sense inside the network. Run it inside the app container, where that <code>.env</code> view of the world is true:</p>
<pre><code class="language-bash">./vendor/bin/sail artisan migrate
# or
docker compose exec app php artisan migrate
</code></pre>
<h2>The startup race: it works on the second try</h2>
<p>There is a sneakier version of this error. Right after <code>docker compose up</code>, the app container starts, tries to connect — and fails. You retry a few seconds later and it works. Your settings were fine all along: you connected during the gap between "the container has started" and "MySQL has finished starting and accepts connections".</p>
<p>A plain <code>depends_on: - mysql</code> does <strong>not</strong> fix this — it only waits for the container to start. The durable fix is a healthcheck plus a condition, so the app waits for a <em>ready</em> database:</p>
<pre><code class="language-yaml">services:
  app:
    depends_on:
      mysql:
        condition: service_healthy

  mysql:
    image: mysql:8
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      interval: 5s
      timeout: 5s
      retries: 10
</code></pre>
<h2>The checklist I run through</h2>
<ol>
<li>Am I inside the right container, or on the host? The host in <code>.env</code> must match where the command runs.</li>
<li>Is the host a service name (<code>mysql</code>), not <code>127.0.0.1</code>?</li>
<li>Did MySQL finish starting? Check the container logs, not just <code>docker ps</code>.</li>
<li>After any <code>.env</code> change, did I run <code>php artisan config:clear</code>? A cached config ignores <code>.env</code> completely.</li>
</ol>
<p>Docker did not break your database connection. It just changed what "localhost" means — and once you see that, the error stops being a mystery. The same error has four more causes outside Docker (server down, wrong port, the socket trap, stale config cache), and the full walkthrough of all six is here: <a href="https://rajadevsolutions.online/errors/how-to-fix-sqlstate-hy000-2002-connection-refused-laravel">https://rajadevsolutions.online/errors/how-to-fix-sqlstate-hy000-2002-connection-refused-laravel</a></p>
<p>Have you hit this one after dockerising a project? What fixed it for you?</p>
]]></content:encoded></item><item><title><![CDATA[Laravel Sanctum Token Auth in 15 Minutes: Register, Login, Logout]]></title><description><![CDATA[Token authentication sounds like a big job until you do it once in Laravel. Sanctum ships with Laravel 13, and the whole flow — register, login, protect…]]></description><link>https://rajadevsolutions.hashnode.dev/laravel-sanctum-token-auth-in-15-minutes-register-login-logout</link><guid isPermaLink="true">https://rajadevsolutions.hashnode.dev/laravel-sanctum-token-auth-in-15-minutes-register-login-logout</guid><category><![CDATA[Laravel]]></category><category><![CDATA[PHP]]></category><category><![CDATA[api]]></category><category><![CDATA[authentication]]></category><dc:creator><![CDATA[Raja Hunain]]></dc:creator><pubDate>Sat, 21 Nov 2026 13:10:47 GMT</pubDate><content:encoded><![CDATA[<p>Token authentication sounds like a big job until you do it once in Laravel. Sanctum ships with Laravel 13, and the whole flow — register, login, protect routes, logout — is about 40 lines of code. Here is the complete setup.</p>
<h2>Step 1: Install the API scaffolding</h2>
<pre><code class="language-bash">php artisan install:api
php artisan migrate
</code></pre>
<p>This creates <code>routes/api.php</code> and installs Sanctum. Every route in that file gets the <code>/api</code> prefix automatically.</p>
<h2>Step 2: Give the User model tokens</h2>
<p>Open <code>app/Models/User.php</code> and add the <code>HasApiTokens</code> trait:</p>
<pre><code class="language-php">use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}
</code></pre>
<p>Without this trait, <code>createToken()</code> does not exist and login cannot issue anything.</p>
<h2>Step 3: Write the login endpoint</h2>
<p>Create an <code>AuthController</code>. The login method validates the credentials, checks the password hash, and issues a token:</p>
<pre><code class="language-php">public function login(Request $request)
{
    $request-&gt;validate([
        'email' =&gt; 'required|email',
        'password' =&gt; 'required',
    ]);

    $user = User::where('email', $request-&gt;email)-&gt;first();

    if (! $user || ! Hash::check($request-&gt;password, $user-&gt;password)) {
        return response()-&gt;json(['message' =&gt; 'Invalid credentials.'], 401);
    }

    $token = $user-&gt;createToken('api-token')-&gt;plainTextToken;

    return response()-&gt;json(['token' =&gt; $token, 'user' =&gt; $user]);
}
</code></pre>
<p>Two things to notice. First, the plain-text token is only shown once, at creation — Sanctum stores only a hash, so if the client loses it, you issue a new one. Second, a wrong password returns <code>401</code>, not a redirect, because this is an API.</p>
<h2>Step 4: Protect the routes</h2>
<p>Register the auth routes as public, and put everything else behind <code>auth:sanctum</code>:</p>
<pre><code class="language-php">Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

Route::middleware('auth:sanctum')-&gt;group(function () {
    Route::apiResource('posts', PostController::class);
    Route::post('/logout', [AuthController::class, 'logout']);
});
</code></pre>
<h2>Step 5: Use the token, then revoke it</h2>
<p>The client sends the token on every protected request:</p>
<pre><code>Authorization: Bearer &lt;token&gt;
</code></pre>
<p>A request without it gets <code>401 Unauthenticated</code>. Logout is one line — delete the token that made this request:</p>
<pre><code class="language-php">$request-&gt;user()-&gt;currentAccessToken()-&gt;delete();
</code></pre>
<p>Only the current token dies. Tokens on the user's other devices keep working, which is exactly what you want.</p>
<h2>Three mistakes to avoid</h2>
<ul>
<li><strong>Forgetting the <code>Accept: application/json</code> header.</strong> Without it Laravel treats the call as a browser request and you get the infamous <code>Route [login] not defined</code> error.</li>
<li><strong>Returning the user model raw.</strong> Wrap it in a Resource or at least hide the sensitive fields — never leak <code>password</code> or <code>remember_token</code> in a JSON response.</li>
<li><strong>One token named the same for everything.</strong> Give tokens descriptive names per device or client (<code>api-token</code>, <code>mobile-app</code>) so you can revoke one without killing the others.</li>
</ul>
<h2>Where this fits</h2>
<p>Auth is one piece of a full API. The complete build — model, migration, API Resources, validation, all five CRUD endpoints and curl tests — is written up step by step here: <a href="https://rajadevsolutions.online/blog/how-to-create-a-rest-api-in-laravel-13">https://rajadevsolutions.online/blog/how-to-create-a-rest-api-in-laravel-13</a></p>
<p>Fifteen minutes, one trait, one controller, and your API has real login. What took you the longest when you set up auth for the first time?</p>
]]></content:encoded></item></channel></rss>