Use Laravel's remember_token as a Revocation Signal
Use Laravel's remember_token as an invalidation signal for saved account-switching state without maintaining a dedicated token or revocation table.
Practical engineering tips for Laravel developers and the wider PHP ecosystem.
Got a tip in mind? Contributions are always welcome.
Use Laravel's remember_token as an invalidation signal for saved account-switching state without maintaining a dedicated token or revocation table.
A practical comparison of Git Submodules and Git Subtrees to help you choose the right strategy for embedding one repository inside another.
Cache browser binaries with actions/cache to avoid downloading 150MB+ on every CI run.
Compare generated content against existing files before writing. This prevents unnecessary git diffs, cache invalidation, and downstream rebuilds.
File modification timestamps are unreliable in GitHub Actions. Use git diff to detect actual changes and conditionally skip expensive workflow steps.
Keep query bindings out of QueryException messages while retaining access to the actual bindings.
Use .git/info/exclude to ignore personal scratch files, local debug scripts, and notes without polluting your team's shared .gitignore file.
Combine response()->streamDownload(), php://output, and query chunking to stream CSV exports directly to the browser without writing temporary files to disk.
Fix common navigation bar layout shifts, scrollbar jumps, font width shifts, and theme switcher flickering with clean CSS and HTML patterns.
Use repository_dispatch to trigger a workflow in a target repository when commits or PRs land in a source repository.
Extend Laravel's Blueprint class with custom macros to standardize and reuse common schema columns across database migrations.
Register reusable query methods directly on the Builder so every model gains access without repeating logic.
Placing a return statement inside a try-catch finally block silently overrides exceptions and previous return statements.
Use Rector rules to automatically convert immutable DTOs and value objects into native PHP 8.2 readonly classes.
When you expect exactly one matching record, use sole() instead of firstOrFail(). It guards against multiple records by throwing MultipleRecordsFoundException.
Use Laravel's Prohibitable trait on custom Artisan commands to selectively block AI agents from running destructive domain operations.
Laravel's AgentDetector detects whether an AI coding agent is interacting with your app, and PAO optimizes CLI output for agents.
cursor() hydrates single model instances sequentially using database cursors; lazy() streams records in chunks backed by LazyCollection.
Understand offset vs keyset pagination when processing large datasets to avoid missing records during updates.
Hiding buttons in Blade or Vue does not restrict access. Always enforce authorization policies in controller or request layers.
Use DB::afterCommit() to defer job dispatching until surrounding database transactions complete successfully.
In Laravel and Pest tests, assertDatabaseHas() natively queries nested JSON properties using arrow syntax and accepts backed Enum instances directly.
Enable the Tia Engine in Pest to only re-run tests affected by your latest code changes while replaying cached results for unaffected tests.
Prevent catastrophic accidents like db:wipe or migrate:fresh in production using Laravel's Prohibitable trait and DB::prohibitDestructiveCommands().
strip_tags() removes HTML elements but fails to sanitize inline attributes or malformed HTML payload vectors. Use HTMLPurifier for rich text input.
Process complex data sequences or multi-stage order checks through Laravel's built-in Pipeline facade to replace massive controller methods.
Use a custom Rector rule to automatically strip noisy inline comments and empty docblocks across your codebase while preserving essential PHPDoc annotations.
Use the $deleteWhenMissingModels property on queued jobs to silently discard jobs if their referenced database records were deleted before execution.
Use withoutRelations() when passing models to queue jobs to prevent large in-memory relationship graphs from serializing into queue storage.
Use queue:work with appropriate sleep configuration or Redis blocking pops to reduce database CPU polling overheads.
The --stop-when-empty-for option keeps queue workers alive for a specific grace period after the queue empties, preventing rapid process churn during bursty workloads.
Replace whereYear() and whereMonth() on large database tables with whereBetween() date ranges to enable SQL index lookups.
Use Cache::memo() to combine persistent cache stores with per-request memory caching, preventing repetitive network roundtrips during a single HTTP request.
Use virtualAs() and storedAs() in migrations to create generated database columns for high-speed indexing on JSON attributes.
Interrupt long-running synchronous PHP callables on any operating system using PHP tick declarations and tick callback functions without requiring the pcntl extension.
Use DB::whenQueryingForLongerThan() to monitor the cumulative time spent in database queries per HTTP request and notify developers of slow requests.
Extract query filtering logic into invokable scope classes that work interchangeably across Eloquent query builders and Laravel Scout search instances.
Use $this->travelTo() or freezeTime() in test suites to test date-sensitive logic without slowing down test execution with sleep().
When creating integer-backed PHP Enums, index starting from 1 to avoid false-y evaluation bugs in loose comparisons.
Document and enforce structured array schemas using PHPDoc array shapes, lists, and non-empty array annotations for static analysis in PHPStan and Psalm.
Implement type-safe generic collections, wrapper classes, and utility functions in PHP using PHPDoc template annotations for static analysis engines.
Understand what each rule level in PHPStan inspects, from basic syntax errors at Level 0 to strict mixed-type enforcement at Level 9 and Level 10.
Use Response::denyAsNotFound() in policies to return a 404 Not Found response instead of 403 Forbidden, concealing the existence of private resources.
Use Laravel's Pipeline facade to pass objects through sequential pipe classes, keeping complex order processing and data transformations modular.
Enable Model::preventLazyLoading() in local development to automatically throw exceptions whenever a relationship is lazy loaded.
Automate renaming PHP 8.1+ enum cases from SNAKE_CASE to PascalCase across PHP classes and Blade templates using Rector and an Artisan refactoring script.
Use Rector to automatically refactor legacy protected $casts array properties into the modern casts() method across your entire Laravel codebase.
Cast enum instances nested within JSON or array database columns using Eloquent Attribute accessors and mutators.
Use Eloquent custom casts (CastsAttributes) to handle complex JSON serialization and Backed Enum arrays cleanly.
Prevent view compilation glitches when running php artisan view:cache on templates using @teleport by registering explicit Blade directives.
Capture HTTP requests, Artisan CLI commands, and outgoing API responses into a unified audit trail using a single Laravel Event Subscriber.
Generate unique database slugs in Eloquent by querying the maximum existing numerical suffix directly instead of executing repeated queries in a while loop.
Control system time during testing and development using Carbon::setTestNow() and inspect active time mocks with Carbon::hasTestNow().
Use Livewire 3's #[Renderless] attribute to stream file downloads directly from component actions without triggering unnecessary view re-renders or database queries.
Automatically assign tenant IDs and restrict Eloquent queries using a reusable BelongsToTeam model trait with model booting and global scopes.
Simplify multi-column wildcard searches across model columns, relationships, and raw SQL expressions using a powerful whereLike macro on the Eloquent Builder.
Use LazilyRefreshDatabase instead of RefreshDatabase to run database transactions only for tests that actually touch the database.
Use Factory::recycle() to pass existing parent models to child factories, avoiding duplicate database record creation in test fixtures.
MySQL prevents updating a table while selecting from it in a subquery. Wrap subqueries in an intermediate alias table.
Use when(), unless(), and whenEmpty() on Laravel Collections to conditionally apply transformations without breaking method chains.
Enable Http::preventStrayRequests() in test suites to throw exceptions whenever HTTP requests are made without explicit mocks.
Query related models located on different database connections using whereHas() without cross-database join errors.
Define relationships on models where foreign keys are stored as JSON arrays or comma-separated lists rather than traditional single-id foreign keys.
Replace PHP's native sleep() and usleep() with Laravel's Sleep facade to write testable, fakeable time pauses.
Use CSS Container Queries (@container) to adjust component layouts based on parent container width rather than viewport size.
Use DB::listen() in AppServiceProvider to monitor executed queries, log slow operations, and inspect raw SQL bindings during local development.
Try adjusting your search query or choosing another category/topic filter.
// Got a tip or want to contribute? github.com/MrPunyapal/tips