开发者
Dev Log: 2026-06-29
TL;DR Two threads today: an organization layer on top of an existing multi-tenant app, and driver-based password-reset backends in an identity portal. Both came down to the same idea — put the source of truth in the right place, then test it. Multi-tenant app: an organization layer above tenancy The product already had tenancy. What it lacked was a human-friendly layer on top: organizations users actually belong to, can switch between, and manage. What landed: Area Change Org switcher A sidebar switcher to move between organizations you belong to Management Create/update org, invitations, ownership transfer Tenancy Resolve the active tenant from the user's org — closed a leak UI Dark-mode pass + responsive fixes across the org views Dashboards Richer per-widget configuration from the UI The standout is the tenancy fix: the active tenant was being resolved from the request instead of the authenticated user. I pulled that into its own focused post — "Resolve the tenant from the user, not the request." Short version: if a value scopes data, it can't come from something the client controls. Identity portal: make the reset backends swappable The password-reset flow needed to support more than one backend, and let an admin decide the order they run in. Classic case for a driver-based abstraction — a contract plus interchangeable drivers, picked at runtime from config. interface PasswordResetBackend { public function reset ( User $user , string $password ): void ; public function name (): string ; } Two optional backends came back as drivers behind that contract, and the run order is now admin-reorderable instead of hard-coded. Adding a third backend later is a new class + a config line — no touching the flow itself. The other half of the day was unglamorous but necessary: the test suite had drifted — stale tests for removed features, and env leakage between tests (one test's state bleeding into the next). Fixed the leakage, deleted the dead tests, and the suite is honest
AI 资讯
Dev Log: 2026-06-28
TL;DR Centred a sidebar brand mark in the collapsed rail (open-source starter kit) — pure CSS, no JS. A CRM app got a "daily cockpit" dashboard (hot leads + overdue follow-ups) plus a full favicon/PWA icon set. An analytics product's ingest pipeline learned to handle messy uploads — files with no date column and no numeric measure — and a nasty metrics bug got squashed. A spread day across three repos. Quick tour. Centring a collapsed sidebar logo (CSS only) Kickoff , my open-source Laravel starter kit, had a small visual snag: when the sidebar collapses to a narrow rail, the header switches to a column — but the brand mark sat off-centre. The content area is ~72px, yet the logo kept its width and a leftover space-x margin, nudging it left of the nav icons. No JavaScript needed. Make the logo and toggle full-width, centre their content, and zero the leftover child margins when collapsed: [ data-flux-sidebar ][ data-collapsed ] .sidebar-header .app-logo { width : 100% ; justify-content : center ; padding-inline : 0 ; } /* kill the leftover space-x margin pushing it off-centre */ [ data-flux-sidebar ][ data-collapsed ] .sidebar-header .app-logo > * { margin : 0 ; } Lesson: when a flex container changes direction, old horizontal margins don't disappear — they just push things in the new axis. Tag the element, scope the override to the collapsed state, done. A CRM "daily cockpit" A CRM app I work on got a dashboard rebuild: instead of a generic landing screen, the first thing you see is what needs action today — hot leads and overdue follow-ups. The cockpit framing matters more than the widgets: surface the work, don't make people hunt for it. Also shipped a full favicon/PWA icon set and a branded responsive landing page, with feature tests so the brand pass didn't quietly break routing. Ingest that survives real-world files The bigger chunk of the day went into an analytics/dashboard product's ingest pipeline. Real uploads are messy, so the pipeline now copes with the
AI 资讯
Seu código de validação de CPF tá gritando por socorro (e você nem percebeu)
Deixa eu adivinhar. Você tá com um projeto Laravel rodando, tem uns 5, 10, talvez 15 formulários que recebem CPF. Cadastro de cliente, cadastro de fornecedor, atualização de perfil, checkout, área administrativa… e em cada um desses lugares tem aquela mesma lógica de validação de CPF. Copiada. Colada. Com pequenas variações. E tá tudo bem. Até o dia em que o cliente pede pra mudar uma regra. Ou um bug aparece em um formulário e funciona normal no outro. Aí você abre o projeto, dá um Ctrl+Shift+F procurando "cpf" e… surpresa: tem oito lugares diferentes com a mesma validação. Com mensagens de erro escritas de oito jeitos. Uma delas até com erro de digitação. Já passou por isso? Então senta que essa conversa é pra você. O crime acontecendo em câmera lenta Olha esse cenário aqui, que eu garanto que você já viu (ou escreveu): // app/Http/Requests/StoreClienteRequest.php public function rules () { return [ 'cpf' => [ 'required' , function ( $attribute , $value , $fail ) { $cpf = preg_replace ( '/[^0-9]/' , '' , $value ); if ( strlen ( $cpf ) !== 11 ) { $fail ( 'CPF inválido.' ); return ; } // ... mais 20 linhas do algoritmo }], ]; } E aí, três dias depois, no outro Form Request: // app/Http/Requests/StoreFornecedorRequest.php public function rules () { return [ 'cpf' => [ 'required' , function ( $attribute , $value , $fail ) { $cpf = preg_replace ( '/[^0-9]/' , '' , $value ); if ( strlen ( $cpf ) !== 11 ) { $fail ( 'O CPF informado não é válido!' ); // mensagem diferente, claro return ; } // ... mais 20 linhas quase iguais, mas não exatamente }], ]; } Multiplica isso por 8 telas. Agora imagina o seu "eu do futuro" tentando manter isso. Dá pra sentir a dor daqui. DRY: a sigla que vai salvar seu projeto (e sua sanidade) DRY significa Don't Repeat Yourself . Em bom português: não se repita, caramba. A ideia é simples: cada pedaço de conhecimento (uma regra de negócio, um cálculo, uma validação) deve existir em um único lugar no seu sistema. Se precisar mudar, você muda em u
AI 资讯
Laravel API Development in Morocco: Architecture Guide 2026
Laravel API Development in Morocco: Architecture Guide 2026 Laravel remains the #1 PHP framework for API development in 2026 Laravel remains the #1 PHP framework for API development in 2026, and Morocco has become a hub for quality Laravel freelancers and teams. Here is the complete guide to building production-grade APIs with Laravel, based on 40+ projects shipped. Why Laravel for APIs in 2026 Eloquent ORM — most expressive DB layer in any framework Sanctum for SPA/mobile auth (simpler than Passport for most cases) Scout for Meilisearch / Algolia / Elastic full-text search Queues with Horizon for background jobs Octane for performance (Swoole / RoadRunner) Deep ecosystem : Telescope, Pulse, Forge, Vapor REST vs GraphQL — What to Choose Criteria REST GraphQL Learning curve Low Medium-high Caching Easy (HTTP) Complex Over-fetching Common Solved Mobile bandwidth Higher Optimized Best for Public APIs, simple CRUD Complex dashboards, mobile apps My default : REST with Laravel API Resources unless the client has clear GraphQL-specific needs (mobile app with variable fields, highly nested data). Standard Laravel API Architecture app/ ├── Http/ │ ├── Controllers/Api/V1/ │ ├── Requests/ (FormRequest for validation) │ └── Resources/ (API Resources for shaping output) ├── Models/ ├── Services/ (business logic) ├── Repositories/ (optional, if complex queries) ├── Jobs/ └── Events/ Key architectural decisions Versioning via URL (/api/v1/users) not headers — simpler FormRequest for validation (never validate in controller) API Resources for every response (shape, transforms, conditionals) Services layer when controllers exceed 100 lines Dedicated DTOs for complex payloads (spatie/laravel-data) Authentication — Sanctum Setup SPA on same domain : cookie-based, CSRF protected Mobile app / 3rd party : personal access tokens Revocation endpoint for logout Token abilities for granular permissions Rate Limiting & Security RateLimiter facade — per user, per IP, per endpoint CORS : use c
开发者
Laravel From Version 5 To Today: The Framework Grew Up With Us
Have you ever opened an old Laravel 5 project and felt like you were walking into a house where every...
AI 资讯
Giving an AI agent the keys without giving it the building: RBAC + org-scoped MCP tools in Laravel
Exposing your app to an AI agent over MCP is basically handing someone a master keyring and trusting them to only open the doors they're supposed to. That trust is a bug waiting to happen. This week I wired up a batch of MCP tools over a multi-tenant Laravel app, and the whole exercise was really about one question: how do I let an agent drive the app without letting it drive someone else's data? Here's the thing about MCP tools — each one is an endpoint. An agent calls list_events , publish_event , check_in_participant , and your server runs code on the caller's behalf. The moment you have more than one tenant, every single tool needs to answer two questions before it does anything: are you allowed to do this , and are you allowed to do it *here *. Authorization and scope. Skip either and you've built a confused deputy. The trap: ambient scope doesn't exist under token auth In a normal web request, multi-tenancy is comfortable. You've got a logged-in user, a global scope on the model that quietly appends where organization_id = ? , and you mostly forget it's there. Everything Just Works because there's an ambient "current organization" sitting in the session. MCP tools don't have that. The caller authenticates with a token, there's no session, no middleware stack that set up a current-tenant context. If you lean on a global OrganizationScope that reads "the current org" from somewhere, it reads nothing — and a query you assumed was fenced returns every tenant's rows. That's the kind of bug that doesn't throw an error; it just silently leaks. So the rule I settled on: under token auth, never rely on ambient scope. Filter explicitly, every time, in one place. That "one place" is a small trait every event-scoped tool pulls in: trait ResolvesOrgEvents { protected function resolveOrgEvent ( Authenticatable $user , string $uuid ): ?Event { if ( empty ( $user -> organization_id )) { return null ; } return Event :: query () -> withOrganization ( $user -> organization_id )
AI 资讯
Dev Log: 2026-06-23 — Query Cleanups, Real Health Checks, Safer MCP Tools, and Password-Reset Plumbing
A wide day rather than a deep one — four separate threads across a few projects, each with a lesson worth keeping. I'll teach the patterns and keep the specifics generic. The through-line: make the system honest about what it's actually doing — which queries it fires, whether a service is really up, what a tool will do when you call it twice, and in what order a password change should land. The performance thread got big enough that I split it into its own focused post; here's the short version plus the three other threads. Thread 1 — Stop paying for queries you don't use A sustained sweep through an app (and the package behind it) hunting wasted database work. The highlights: Arm an N+1 detector in dev only. A query detector wired in behind an environment check turns invisible lazy-loads into a visible to-do list. Never in production — it's a developer aid, not a runtime guard. Unused eager loads are N+1s in disguise. Index screens love to with(['creator', 'approver']) for columns a redesign later removed. Not a loop, but the same disease: queries you hydrate and throw away. Delete the eager loads with no consumer in the view. Memoize per-request constants. A default-connection resolver and a sidebar unread count were both recomputed on every call. ??= once, reuse for the rest of the request. Collapse a dashboard's stat queries. ~20 count() calls became one grouped query per table, wrapped in a short-lived cache. A dashboard can tolerate being a few seconds stale; trade live-to-the-second for cheap. The meta-lesson: performance at this layer is mostly removal , and you lock it in with a Pest query-count assertion so nobody quietly re-adds an N+1 six months later. Full write-up in the focused post. Thread 2 — Health checks that actually check Here's a trap I keep seeing in "is it up?" tooling: the check verifies the record exists, or that a config row is present, and calls it green. That's not a health check — that's a config check. The service can be configured per
AI 资讯
A Day of Performance Hardening: Hunting N+1s and Killing Wasted Queries in Laravel
Performance work has a reputation for being glamorous — the heroic "we cut latency by 80%" story. Most days it's not that. Most days it's a janitorial pass: you go looking for the queries you're firing without realizing it, and you quietly delete them. That was today. One sustained sweep across an app and the package that backs it, chasing the same theme everywhere: stop asking the database for things you don't use. Let me walk through the patterns, because they generalize to any Laravel app of a certain age. First, make the invisible visible You can't fix N+1s you can't see. The first move was wiring up an N+1 detector in the local/dev environment only — beyondcode/laravel-query-detector . It hooks into the request lifecycle, watches your Eloquent relationship loads, and screams (in the console, or as an exception if you want it strict) when it spots the classic loop-and-lazy-load pattern. The "dev-only" part matters. You never want a query detector running in production — it adds overhead and it's a developer aid, not a runtime guard. So it goes in behind an environment check, registered only when the app isn't in production: public function register (): void { if ( $this -> app -> environment ( 'local' , 'testing' )) { $this -> app -> register ( \BeyondCode\QueryDetector\QueryDetectorServiceProvider :: class ); } } Think of it like a smoke detector you only arm while you're cooking. It's noisy by design — that's the point. The noise is a to-do list. Eager loads you don't actually use are just N+1s wearing a disguise Here's the counterintuitive one. We're all trained to fix N+1s by adding with() . But the opposite bug is just as common and almost never gets caught: you eager-load a relationship, and then... never touch it in the view. Index screens are the worst offenders. Someone builds a listing, eager-loads creator and approver so the table can show names, then a redesign drops those columns — but the with(['creator', 'approver']) stays. Now every page load hyd
AI 资讯
Dev Log: 2026-06-22 — Configurable Schedulers, Load-Test Toolkits, and an MCP Server
Some days the work spreads across a few projects instead of landing as one big feature. Today was that — three distinct threads, each with a lesson worth keeping. I'll keep things generic and teach the pattern rather than the project, but the through-line is the same: move things that were hardcoded or ephemeral into something you can configure, repeat, and trust. Thread 1 — Make scheduled tasks configurable instead of code-only If you've run a Laravel app for any length of time, you know the scheduler lives in code: routes/console.php or the kernel, a wall of ->daily() , ->everyFiveMinutes() , ->cron(...) . That's fine until the day an operator — not a developer — needs to change when something runs. Then you're shipping a deploy just to nudge a cron expression. Silly. Today's work pulled scheduler configuration into a settings-backed UI. The pattern is worth stealing: instead of the schedule being a literal in code, the code reads its cadence from a settings store, and there's an admin screen to edit it. // Instead of a hardcoded cadence... $schedule -> command ( 'subscriptions:reconcile' ) -> daily (); // ...read it from settings, with a sane default baked in. $schedule -> command ( 'subscriptions:reconcile' ) -> cron ( $this -> schedulerSettings -> reconcileCron ?? '0 2 * * *' ); Two things made this clean. First, a SchedulerSettings object (Spatie's settings pattern) so the values are typed, cached, and migratable — not loose rows you Setting::get('...') by string key. Second, grouping the more user-facing schedules behind their own modal rather than dumping every cron in one giant form. A subscription-related schedule belongs next to subscriptions; a platform schedule belongs in admin. Same data, but organized by who needs to touch it . The edge case to watch: a UI-editable cron is a foot-gun if you let people type nonsense. Validate the expression on save, and always keep a default so a blank setting can never silently disable a job. Thread 2 — A load-testing
开发者
bcrypt and Laravel: 72 Bytes, Not 72 Characters
I expected bcrypt to silently drop characters past 72. I did not expect it to bake in half an emoji. That's what happens with a specific password combination I tested. The original password still works. But strip the emoji (a password manager, a different keyboard, a Unicode normalizer) and you're locked out. Your Laravel validator passed it as valid the whole time. The 72-Byte Rule bcrypt has a hard input limit of 72 bytes. Not characters - bytes. When you call password_hash($password, PASSWORD_BCRYPT) , PHP silently truncates anything past byte 72. Most developers know this in theory. But for ASCII-only apps, it never bites. 72 ASCII characters is already a very long password, and the silent clip is harmless in practice. The trouble starts with multi-byte scripts. How Many Characters Fit? Character set Bytes per char Effective bcrypt limit ASCII 1 72 chars Cyrillic 2 36 chars CJK (Chinese, Japanese, Korean, common block) 3 24 chars Emoji 4 18 chars Past the byte limit, a longer password adds no security at all. A 200-character Cyrillic password hashes identically to its own first 36 characters. Byte 73 and beyond simply do not exist from bcrypt's point of view. So "longer always produces a stronger bcrypt hash" is not true. A Cyrillic user with a 37-character password gets silently truncated at char 36. The hash is still consistent. The user logs in fine, but any variation past character 36 doesn't matter to bcrypt. Annoying from a security standpoint, but it does not break login. The Split-Byte Trap The 72-byte limit cuts at a byte boundary, not a character boundary. If a multi-byte character falls on that cut, bcrypt bakes in an incomplete UTF-8 sequence. // 35 Cyrillic chars = 70 bytes, emoji = 4 bytes, total = 74 bytes $password = str_repeat ( 'А' , 35 ) . '🔑' ; $hash = password_hash ( $password , PASSWORD_BCRYPT ); password_verify ( $password , $hash ); // ? password_verify ( str_repeat ( 'А' , 35 ), $hash ); // ? password_verify ( str_repeat ( 'А' , 36 ), $h
AI 资讯
Extending Filament exports with Laravel Excel
Filament's export action is great. It's quick to set up, supports queued exports, includes column mapping, handles notifications, and keeps a history of generated files through the Export model. For most use cases, it's exactly what you need. But I recently ran into a limitation that the native export couldn't solve. When XLSX isn't really Excel I was exporting financial data or measurements from a Filament table. The export worked. The file downloaded. Excel opened it without any issue. The problem was that every amount was exported as text instead of a real numeric value. For an accountant, that creates several problems immediately: Excel formulas such as =SUM() don't work correctly Selecting a range of cells doesn't display totals in Excel's status bar Conditional formatting based on numeric values becomes unreliable Additional manual cleanup is required before the file can be used Technically the export contained the data. Practically, it wasn't usable. The root cause is simple: Filament's export system is designed around CSV-style exports. That's perfect for many scenarios, but it doesn't expose the full spreadsheet capabilities offered by PhpSpreadsheet and Laravel Excel . On top of that, I also had a second, completely different requirement: a yearly report with one worksheet per month, merged headers, borders, conditional formatting, and custom layouts. Not a table dump but a report. Why not just use Laravel Excel directly? Laravel Excel already solves all of these problems. It's built on PhpSpreadsheet and provides complete control over cell types, number formats, formulas, styling, and multiple worksheets. The obvious solution would have been to abandon Filament's export action entirely and build custom exports from scratch. But that means losing everything Filament already provides: Export modal and options form Column mapping UI Queue handling Progress notifications Download links Export model history I didn't want to rebuild all of that. I simply wanted
AI 资讯
The Tips Behind API Artisan: Building Laravel APIs Developers Actually Want to Use
I have just finished writing API Artisan: A Guide to Building APIs with Laravel , and I am giving it away for free. Before you commit to 300-odd pages, let me give you the short version: the tips, patterns, and small decisions that separate an API that technically works from one that developers are genuinely happy to depend on. None of this needs more hardware, a different framework, or a bigger team. It needs you to point your attention at the right things. These are the ones I keep coming back to. Start by measuring the right thing Ask most teams how they know their API is good and you get a single question back: does it work? Can I hit this endpoint and get a response? That question is necessary, and it is nowhere near enough. The question I want you to ask instead is whether your API is liveable with. Can a developer read your docs, understand your auth model, make a successful request, and handle an error without contacting support, trawling a forum, or guessing what a status code is trying to tell them? The gap between "works" and "liveable with" never shows up in a sprint retro, but it shows up everywhere else: in support volume, in integration timelines that overrun, and in the quiet moment a developer decides to build around your API rather than with it. Everything else in the book hangs off one mindset shift: an API is a product. It has users. Treat it as an implementation detail and it will behave like one. It will change without warning when your internals change, and it will be inconsistent because different people wrote different parts on different days with different conventions. Write the contract before the code The natural way to build an endpoint is to write the handler, return some data, and document it afterwards if there is time. It feels efficient, and in the short term it is. The problem is what it produces: a contract that was never designed, only discovered. Let me show you the trap, because I have watched it catch good developers. You have
AI 资讯
How a Five Line Architecture Test Caught a Data Leak a Code Review Missed
TL;DR: Pest PHP can test the structure of your code, not just its behavior. Write your team rules as architecture tests and CI enforces them on every commit. One such test caught a multi-tenant data leak that a human review had missed. We had a rule. Every model holding tenant-specific data must use our BelongsToTenant trait. That trait adds the global scope that keeps one clinic from seeing another clinic's data. The rule was in onboarding. It was in the code review checklist. Everyone knew it. A developer joined the team. Three weeks in they added a new model and forgot the trait. The reviewer was focused on the business logic, which was genuinely well written, and did not notice the missing trait. The model shipped. For two days one clinic could see fragments of another clinic's data in one specific report. A support ticket caught it. Our tests did not. That was the day architecture tests went into the project. What an Architecture Test Is Most tests check behavior. Given this input the function returns that output. An architecture test checks structure instead. It asserts things about how the code is organized rather than what it computes. Pest has an arch function for exactly this. // tests/Architecture/ArchTest.php arch ( 'tenant models must use the BelongsToTenant trait' ) -> expect ( 'App\Models' ) -> toUseTrait ( 'App\Traits\BelongsToTenant' ) -> ignoring ( 'App\Models\SystemSetting' ); arch ( 'controllers may not touch the DB facade directly' ) -> expect ( 'App\Http\Controllers' ) -> not -> toUse ( 'Illuminate\Support\Facades\DB' ); arch ( 'services may not depend on the HTTP request' ) -> expect ( 'App\Services' ) -> not -> toUse ( 'Illuminate\Http\Request' ); arch ( 'no env calls outside config files' ) -> expect ( 'App' ) -> not -> toUse ( 'env' ); These run in CI on every commit. Break a rule and the build fails with a message naming the rule and the file that broke it. The Tests That Earned Their Keep The tenant trait test caught four more models over
AI 资讯
Composer Update Is Not Safe Anymore
Saturday morning. I opened Twitter and saw a tweet about the Laravel-Lang packages being compromised. My first reaction was simple: "I don't use that package." Then I opened composer.json on a project I work on and found this in require-dev : "laravel-lang/lang" : "^14.8" , "laravel-lang/publisher" : "^16.8" , That changed things. What Actually Happened The attack used laravel-lang packages as the distribution channel. And the sneaky part: the main repository branch looked completely clean. No suspicious commits, no new code. The malicious payload was pushed via git tags on forks . Most developers would not notice anything. Just a routine composer update , same as always. Once installed, the payload executed at autoload time . That means every php artisan command, queue worker, or web request running that codebase triggered the malware the moment PHP hit require_once __DIR__.'/../vendor/autoload.php' in public/index.php . Silently. No error, no red screen, nothing. The malware was a credential stealer. It searched the machine for: .env files from Laravel projects AWS access keys and session tokens SSH private keys GitHub CLI tokens NPM tokens Infrastructure secrets This is not a SQL injection that messes with your database rows. This is a key stealer that runs on your machine and takes everything it finds. Aikido Security caught it and reported it to Packagist. Packagist removed the affected versions. But if you ran composer update during that window, you were exposed. Why Supply Chain Attacks Are Different Classic Laravel security talks about SQL injection, XSS, CSRF. Those are attacks that come from outside users sending malicious input to your application. Supply chain attacks come from inside your own development process. The attacker does not need to find a vulnerability in your code. They need to compromise one developer account at one package maintainer. Every project depending on that package is now exposed. With AI tools, these attacks are getting more soph
AI 资讯
One Nullable Timestamp, Four Account States: Deriving User Status in Laravel
Most of today went into a user-management overhaul in kickoff — my Laravel starter kit. Flyout CRUD panels, bulk actions, permission assignment, and the piece I want to talk about: account status . Active, suspended, unverified, deleted. The interesting part isn't the feature. It's the modelling decision underneath it. Where do those four states actually live ? The trap: a status column The obvious move is a status enum column on users . Set it to suspended when you suspend someone, active when you reinstate, unverified until they verify their email, deleted when they're soft-deleted. It works. Until it doesn't. Now you've got a status column and an email_verified_at column and a deleted_at from soft deletes — and all three encode overlapping truths. Soft-delete a user and forget to flip status ? Now your database says the account is both active and trashed. Verify an email but the status update fails mid-request? Drift. Every place that mutates a user becomes a place that has to remember to keep status in sync. That's not a feature, that's a maintenance tax. The signals already exist. email_verified_at tells you verified-or-not. deleted_at (soft deletes) tells you removed-or-not. The only genuinely new state is suspended — an admin deliberately blocking sign-in. So that's the only thing worth storing. What we actually store: one nullable timestamp Schema :: table ( 'users' , function ( Blueprint $table ) { $table -> timestamp ( 'suspended_at' ) -> nullable () -> after ( 'email_verified_at' ); }); That's the whole migration. Not a boolean is_suspended — a nullable timestamp. Null means not suspended; a value means suspended and tells you when. A boolean throws that second fact away for free; the timestamp keeps it at no extra cost. Same instinct as email_verified_at and deleted_at — Laravel models "did this happen, and when" as a nullable timestamp everywhere, so we follow the grain of the framework. The behaviour on the model stays tiny: public function isSuspended
AI 资讯
Why an encrypted config backup breaks when you move servers — and how I fixed it in laravel-config-backup
Imagine you write a letter in a secret code that only your old house key can read. Then you move. You photocopy the coded letter, carry it to the new house… and realise the new key can't decode any of it. The letter is valid, just useless. That's effectively what happens when you back up encrypted values from a Laravel database and restore them onto a different server. I hit exactly this while working on laravel-config-backup today, so here's the problem and the fix. The real cause: Crypt is bound to APP_KEY When you store sensitive settings (think API tokens or OAuth secrets) in the database, you typically encrypt them with Crypt::encryptString() . Lovely — until you remember Crypt uses your app's APP_KEY as the key. A naive backup copies that ciphertext straight across: // Naive approach — move the ciphertext as-is $value = DB :: table ( 'settings' ) -> where ( 'key' , 'some.secret' ) -> value ( 'value' ); // this value is encrypted with the OLD server's APP_KEY The new server has a different APP_KEY . Try to decrypt → DecryptException: The payload is invalid . Your backup is technically complete but practically dead. The fix: decrypt on the way out, re-encrypt on the way in The decision is easy to state, hard to stay disciplined about: never carry ciphertext across a server boundary. Instead — On create : decrypt the values with the source server's APP_KEY , store plaintext inside the archive. Protect that archive with AES-256 and a password (a human-held secret, not the APP_KEY). On restore : re-encrypt the values with the destination server's APP_KEY before writing to the DB. Back to the analogy: you decode the letter, carry the plain letter in a locked briefcase (the password-protected archive), and re-encode it with the new house's lock on arrival. The briefcase handles security in transit — not the old code that's no longer relevant. I made that intent explicit right where the behaviour lives, in ConfigBackupService : /** * Config Backup & Restore. * * Bundl
AI 资讯
Shipping a Livewire 4 + Flux admin UI inside a package: four gotchas that 500'd on me
Bundling an admin UI inside a Laravel package is a different game from building one in an app. The app's conveniences — a compiled Vite manifest, a registered layout, your own Livewire components — aren't there. Today, getting the bundled admin UI in laravel-config-webhook to actually render meant walking through four separate 500s. Each one is a small, sharp lesson about the boundary between a package and its host app. 1. A Livewire 4 component name can't contain :: I registered the component with a namespaced-looking name and got a ComponentNotFoundException at runtime. The cause is subtle: under Livewire 4, a name containing :: triggers namespace resolution that ignores singly-registered components. So a "nice looking" name silently routes to a lookup that will never find it. The fix is to register a plain, dotted name: // ❌ looks tidy, but the "::" sends Livewire down a namespace path Livewire :: component ( 'config-webhook::webhooks' , Webhooks :: class ); // ✅ a flat dotted name resolves to the singly-registered component Livewire :: component ( 'config-webhook.webhooks' , Webhooks :: class ); Lesson: in a package, treat the component name as an identifier with framework-reserved characters — :: is not yours to use. 2. Flux ships Heroicons, not Pro/Lucide names The free tier of Flux ships Heroicons . Reach for a Pro-only or Lucide-style name and it throws at runtime. I'd used webhook , ellipsis , and list ; the free equivalents are bolt , ellipsis-horizontal , and queue-list . This is the same trap that bit my SSO package — which is exactly why I now guard it with a static test that reads the Blade and checks every icon against Flux's actual stub files. (Separate post on that.) If you ship a package UI with Flux, assume free-tier icons only unless you require Pro. 3. Don't @vite host assets that don't exist The bundled fallback layout @vite -d the host app's assets. In a fresh consumer (or the package's own workbench) there's no compiled manifest, so you get a
AI 资讯
A test that catches the bug your feature tests can't see
There's a class of bug that's maddening: it passes every test you have, then crashes in the user's face. I hit one in the admin UI of laravel-config-sso today, and the real fix wasn't changing an icon name — it was writing a test that could see the bug in the first place. The bug: wrong icon name, crashes only at runtime The admin UI uses Flux . Flux resolves icons through <flux:delegate-component> , and it throws for a name that doesn't exist: Flux component [icon.ellipsis] does not exist. It's an easy mistake. Flux ships Heroicons , not Lucide. So your Lucide reflexes lie to you: You type (Lucide) Flux wants (Heroicon) ellipsis ellipsis-horizontal trash-2 trash eye-off eye-slash Why feature tests don't catch it Here's the interesting part. I had a feature test that hits the admin route and asserts 200. Green. But the real UI crashes. How? Because in the headless test harness, Flux renders icons as no-ops. No real <flux:delegate-component> boots, so the icon name never gets resolved. The crash only surfaces under a full boot ( testbench serve ) — exactly where your automated tests don't go. Analogy: it's like a spell-checker that only runs when you print the document, not while you type. Your tests type away happily. The crash waits at the printer. The fix: a static test that reads the Blade and validates every icon Instead of relying on runtime, I wrote a Pest test that reads the Blade view, extracts every icon name (static and inside dynamic expressions), and asserts Flux actually ships a stub for each one: $fluxIconStubs = base_path ( 'vendor/livewire/flux/stubs/resources/views/flux/icon' ); it ( 'only references Flux icons that exist' , function () use ( $fluxIconStubs ) { expect ( is_dir ( $fluxIconStubs )) -> toBeTrue ( "Flux icon stubs not found" ); $view = file_get_contents ( __DIR__ . '/../../resources/views/livewire/sso-providers.blade.php' ); // Static `icon="name"` plus quoted tokens inside dynamic // `icon="{{ $cond ? 'eye-slash' : 'eye' }}"` expressio
AI 资讯
Making encrypted Laravel config backups portable across APP_KEYs
Here's a fun one. You build a package that backs up an app's config — the .env plus the settings stored encrypted in the database — into a single password-protected ZIP. The whole selling point is portability : take a backup on server A, restore it on server B, even when the two servers have different APP_KEY s. Then you write a test that actually changes the key during a restore, and it fails. The DB settings come back garbled. Turns out the bug wasn't in the encryption at all. It was in a cache I forgot was there. Today I shipped 1.1.0 of laravel-config-backup and this portability fix was the headline. Let me walk through it, because the lesson generalizes way beyond this package. Why APP_KEY portability is even a thing Laravel encrypts things with APP_KEY . Encrypted Eloquent casts, signed cookies, sessions — all of it keys off that value. So if you naively mysqldump a table with encrypted columns and load it onto another server, every encrypted column is now ciphertext that the new key can't decrypt. Dead data. The trick this package uses is to store the archive contents decrypted . When I export the database, rows go out through their casts , so an encrypted column becomes a plain value inside the ZIP (the ZIP itself is AES-256 password-encrypted, so it's not sitting around in plaintext). On import, each row is written back through the model , which means the cast re-encrypts it with whatever APP_KEY is active on the destination. Server A (key A) Archive (decrypted) Server B (key B) ──────────────── ─────────────────── ──────────────── settings.payload ──decrypt──▶ "Portable" ──import──▶ settings.payload (ciphertext A) (cast) (cast) (ciphertext B) Think of it like shipping furniture: you don't ship the assembled wardrobe through a doorway it doesn't fit, you flat-pack it and reassemble at the destination with the screws you have there. The restore sequence A restore that also brings a new .env has to be careful about ordering . Here's the real flow: public func
AI 资讯
Build a versioned Laravel API with auto-generated OpenAPI docs in 10 minutes
TL;DR — We'll install dskripchenko/laravel-api , write one controller, and end up with a versioned API ( /api/v1/... ) and interactive OpenAPI 3.0 docs at /api/doc — generated from the docblock you'd write anyway. Then we'll ship a v2 without copy-pasting a single controller. The problem Two things rot in every growing Laravel API: Versioning. v1 ships, then v2 needs to change three endpoints but keep the other twenty. You either copy-paste a V2 folder (and now bugfixes live in two places) or bolt if ($version === 2) branches into your controllers. Docs. The OpenAPI spec drifts from the code the moment you merge. Annotation libraries ( #[OA\Get(...)] , giant YAML files) ask you to describe your API twice — once in code, once in attributes. This package's bet: your controller already describes itself . The method name, the request fields, the response shape — write them once, as a normal PHPDoc, and let the package derive routes and docs from it. Versioning becomes plain PHP inheritance. Let's build it. What we'll build A tiny tasks API: POST /api/v1/task/list — list tasks POST /api/v1/task/create — create one interactive docs at GET /api/doc (raw spec per version at /api/doc/{version} ) then a v2 that adds an endpoint without touching v1 Total: ~4 small files. Step 0 — Install composer require dskripchenko/laravel-api Publish the config (optional, but handy to see the knobs): php artisan vendor:publish --tag = laravel-api-config // config/laravel-api.php return [ 'prefix' => 'api' , // → /api/... 'uri_pattern' => '{version}/{controller}/{action}' , 'available_methods' => [ 'get' , 'post' , 'put' , 'patch' , 'delete' ], 'openapi_path' => 'public/openapi' , 'doc_middleware' => [], // lock down /api/doc here ]; Step 1 — Write a controller Nothing exotic — it extends the package's ApiController , which gives you response helpers ( success() , error() , validationError() , created() , noContent() , notFound() ). The docblock is the documentation : <?php namespace App\Api