Working with JWTs in Laravel (Without the Magic) — Stable…
    Neura MarketNeura Market/Stable Diffusion
    ChatGPTChatGPTClaudeClaudeGeminiGeminiCursorCursorGrokGrokPerplexityPerplexityStable DiffusionStable Diffusion
    DeepSeekDeepSeekCoPilotCoPilotMidjourneyMidjourney
    View All Directories
    OverviewPromptsBlogVideosGuidesCoursesCommunityModelsLoRAsComfyUI WorkflowsTrending
    Stable DiffusionBlogWorking with JWTs in Laravel (Without the Magic)
    Back to Blog
    Working with JWTs in Laravel (Without the Magic)
    laravel

    Working with JWTs in Laravel (Without the Magic)

    Mark Townsend March 30, 2026
    0 views

    If you've worked with APIs, authentication, or third-party integrations, you've almost certainly run...

    If you've worked with APIs, authentication, or third-party integrations, you've almost certainly run into JWTs (JSON Web Tokens).

    JWT (pronounced: JOT) is a compact string used to pass data between systems. It has three base64url-encoded parts separated by dots: header, payload, and signature. The header defines metadata like the algorithm, the payload contains claims such as user id and expiration, and the signature ensures integrity. The header and payload can be decoded into JSON for quick inspection.

    Let's create a simple trait you can use on any class in your Laravel application to read the contents of a JWT:

    <?php
    
    namespace Quartzy\Illuminate\Support\Traits;
    
    use Illuminate\Support\Str;
    
    trait InspectsJwt
    {
        public function inspectJwt(string $jwt): array
        {
            if (!str_contains($jwt, '.')) {
                return [];
            }
    
            return collect(explode('.', $jwt))
                ->map(function (string $segment) {
                    $decoded = base64_decode(
                        Str::of($segment)
                            ->replace('_', '/')
                            ->replace('-', '+')
                            ->__toString()
                    );
    
                    return json_decode($decoded, true) ?? [];
                })
                ->filter() // removes empty payload elements from the array
                ->reduce(fn (array $carry, array $item) => array_merge($carry, $item), []);
        }
    }
    

    Now you can inspect the contents of JWT with ease! Let's look at an example where a user is making a request to our app and their JWT token is passed as a header in the request. This would be our example JWT:

    (You can copy the following JWT and examine it on JWT.io eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2Nzg5MCIsInV1aWQiOiI1NTBlODQwMC1lMjliLTQxZDQtYTcxNi00NDY2NTU0NDAwMDAiLCJuYW1lIjoiTWFyayBUb3duc2VuZCIsImVtYWlsIjoibWFyay50b3duc2VuZEBleGFtcGxlLmNvbSIsInJvbGUiOiJkZXZlbG9wZXIiLCJpYXQiOjE3MTAwMDAwMDAsImV4cCI6MTcxMDAwMzYwMH0.signatureplaceholder

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\Request;
    use Quartzy\Illuminate\Support\Traits\InspectsJwt;
    use App\Models\User;
    use Illuminate\Support\Facades\Log;
    
    class AuthenticateWithJwtUuid
    {
        use InspectsJwt;
    
        public function handle(Request $request, Closure $next)
        {
            $authorization = $request->header('Authorization', '');
    
            if (str_starts_with($authorization, 'Bearer ')) {
                $jwt = substr($authorization, 7);
                $payload = $this->inspectJwt($jwt);
    
                if (!empty($payload['uuid'])) {
                    // Pull user by UUID instead of numeric ID
                    $user = User::where('uuid', $payload['uuid'])->first();
    
                    if ($user) {
                        $request->attributes->set('user', $user);
                        Log::info("JWT authenticated user {$user->name} with role {$payload['role']}");
                    }
                }
            }
    
            return $next($request);
        }
    }
    

    That's all there is to it! Hopefully this helps demystify JWTs and simplifies working with them in your application!

    Tags

    laravelphpsecuritytutorial

    Comments

    More Blog

    View all
    Context bankruptcy: The case for strategic forgetting for AI Agentsai

    Context bankruptcy: The case for strategic forgetting for AI Agents

    Most of us have seen a coding agent fail to complete a task we know it can do. We just don't...

    J
    James O'Reilly
    Parallel Compliance Engine: Drive-to-Sheets Multi-Agent Orchestrationgooglecloud

    Parallel Compliance Engine: Drive-to-Sheets Multi-Agent Orchestration

    When building Generative AI applications, developers often encounter a massive bottleneck: sequential...

    A
    Aryan Irani
    Is It Ethical to Post and Ask About Circuits on Dev.to?discuss

    Is It Ethical to Post and Ask About Circuits on Dev.to?

    I’ve been thinking about sharing some electronic circuit posts on Dev.to — small circuits, DIY...

    C
    codebunny20
    The One-Click Exporter: AI Studio Antigravity, Probed to Its Limitsagents

    The One-Click Exporter: AI Studio Antigravity, Probed to Its Limits

    What nobody tells you about exporting your multi-agent prototype to a local workspace. Every...

    L
    leslysandra
    Guarding the till while autonomous data agents do the diggingagenticarchitect

    Guarding the till while autonomous data agents do the digging

    Autonomous agents are genuinely good at answering messy business questions. Give one an LLM and a set...

    S
    Sireesha Pulipati
    Return on Attention: Why AI Code Reviews Are Wearing Us Outai

    Return on Attention: Why AI Code Reviews Are Wearing Us Out

    PR volume went up, ticket quality didn't, and the gap got filled with LLMs on both sides of the review: bots reviewing, bots replying, bots occasionally arguing with bots about priorities that only existed in a teammate's head. Our CEO named the actual problem, and it's bigger than code review.

    C
    christine

    Stay up to date

    Get the latest Stable Diffusion prompts, rules, and resources delivered to your inbox weekly.

    Neura Market LogoNeura Market

    Discover the best AI prompts, plugins, and resources for Stable Diffusion and more.

    Content Types

    • Rules
    • Prompts
    • MCPs
    • Agents
    • Guides

    Platforms

    • ChatGPT Directory
    • Claude Directory
    • Gemini Directory
    • Cursor Directory
    • Grok Directory
    • Perplexity Directory
    • DeepSeek Directory
    • CoPilot Directory
    • Stable Diffusion Directory
    • Midjourney Directory
    • All Directories

    Resources

    • Blog
    • Documentation
    • Help Center
    • Marketplace

    Legal

    • Privacy Policy
    • Terms of Service

    © 2026 Neura Market. All rights reserved.

    |

    Not affiliated with any AI platform vendors.

    Ready-made automations for this

    Workflows from the Neura Market marketplace related to this Stable Diffusion resource

    • Automate SharePoint List Data Fetching with OAuth Authenticationn8n · $15.99 · Related topic
    • Webhook Response Handling with HMAC SHA256 Authenticationn8n · $4.99 · Related topic
    • Automate Lemlist and Slack Integrations for Enhanced Follow-Upsn8n · $19.99 · Related topic
    • Secure Webhook with API Key Authentication - Essentialn8n · $12.99 · Related topic
    Browse all workflows