tgindex

PHP & Laravel Magic: Mastering Web Development

описание

🔮 Dive into professional web development with PHP and Laravel! Discover: 🛠️ Efficient snippets 📚 Tips and guides 💡 Advanced solutions 🌟 Code optimization methods Subscribe to enhance your skills and master best practices! 🚀

2 216
подписчиков
Охват к подписчикам
81,9%
ERR
Реакции к просмотрам
0,52%
217 на 25 постов
Пересылки к просмотрам
0,30%
123
Постов в день
0,0
всего 25

Где отзываются чаще

доля реакций к просмотрам
  • 12 июл.⚙️ `php artisan dev` in Laravel 13.16 — the end of the `composer dev` era Every Laravel dev knows the ritual: open 4 terminals. → php artisan serve → php artisan queue:work → php artisan pail → npm run dev Someone came up with composer dev — a single command running everything via concurrently. Better. But the config lives in composer.json, no typing, adding your own process means editing JSON by hand. 13.16 moves it into PHP. Register in a service provider: use Illuminate\Foundation\Console\DevCommands; DevCommands::artisan('reverb:start')->orange(); DevCommands::register('stripe listen --forward-to ' . config('app.url'))->green(); Then — one command for the whole stack: php artisan dev Everything spins up: server, queue, logs, vite, reverb, stripe listen — whatever else you added. Each process in its own color in the terminal. What you get over `composer dev` → Config lives in PHP, not JSON — you can use config(), env(), environment conditions → Auto-detects your package manager — bun.lock present → runs via bun, pnpm-lock.yaml → pnpm. No more patching npm scripts per teammate → Packages in vendor/ can't shove themselves into your dev stack — explicit opt-in only → Named processes with colors — readable output, not a firehose of interleaved logs One terminal. One color per process. One config in PHP. You can retire composer dev.1,87%
  • 25 мая🪤 whereHas + withCount: doubling your DB work for nothing Everyone writes this. You probably too: User::whereHas('orders', fn($q) => $q->where('status', 'paid')) ->withCount(['orders' => fn($q) => $q->where('status', 'paid')]) ->get(); "Give me users with paid orders and the count." Reads clean. Here's what the DB actually sees: SELECT *, (SELECT COUNT(*) FROM orders WHERE user_id = users.id AND status = 'paid') as orders_count FROM users WHERE EXISTS ( SELECT * FROM orders WHERE user_id = users.id AND status = 'paid' ) Same subquery. Twice. Same filters. On 50k users and a couple million orders that's +300–500ms per request. On a list endpoint hit hundreds of times a minute — it shows up on your dashboards. Fix — drop `whereHas`. Count first, filter via HAVING: User::withCount(['orders as paid_orders_count' => fn($q) => $q->where('status', 'paid')]) ->having('paid_orders_count', '>', 0) ->get(); One subquery. Same result. Bonus — the count is already there in $user->paid_orders_count. No need to duplicate it in your Blade. This is trap 1 of 3 with whereHas. Next up — soft deletes and cascading EXISTS.1,16%
  • 5 июн.🪤 Nested `whereHas` — the slowest construct in Eloquent If the first two traps were about silent bugs, this one just kills the database. You need users with orders for a specific product: User::whereHas('orders', function ($q) { $q->whereHas('items', function ($q2) { $q2->where('product_id', 5); }); })->get(); Clean. Declarative. Sails through code review. Here's what actually hits the DB: SELECT * FROM users WHERE EXISTS ( SELECT * FROM orders WHERE user_id = users.id AND EXISTS ( SELECT * FROM items WHERE order_id = orders.id AND product_id = 5 ) ) Two nested EXISTS. For every users row, MySQL walks orders. For every order — walks items. N × M × K in the worst case. Real numbers: 100k users, a million orders, 10M items — query holds the DB for 30+ seconds. MySQL's planner barely optimizes nested correlated subqueries — it just brute-forces them. Fix — rewrite as JOIN with DISTINCT: User::join('orders', 'orders.user_id', '=', 'users.id') ->join('items', 'items.order_id', '=', 'orders.id') ->where('items.product_id', 5) ->select('users.*') ->distinct() ->get(); Uglier. 10–30× faster. Same dataset — seconds instead of tens of seconds. Rule of thumb → Single whereHas + proper indexes — fine → Nesting 2+ levels deep — rewrite to JOIN → orWhereHas inside — don't even think, go straight to JOIN Series closed. Eloquent is a great tool — as long as you remember there's SQL underneath.0,89%
  • 28 апр.📎 Laravel PDF 2.6 — Attach PDFs to Emails Without Disk Before, generating PDFs for email looked like this: → Create PDF → Save to disk → Attach to email → Delete file Spatie laravel-pdf 2.6.0 solves this elegantly. Before: $pdf = Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->save(storage_path('temp/invoice.pdf')); $mail->attach(storage_path('temp/invoice.pdf')); unlink(storage_path('temp/invoice.pdf')); After: $pdf = Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->name('invoice.pdf'); $mail->attach($pdf); In Notification: public function toMail($notifiable): MailMessage { $pdf = Pdf::view('pdfs.invoice', ['invoice' => $this->invoice]) ->name('invoice.pdf'); return (new MailMessage) ->subject('Your invoice') ->attach($pdf); } In Mailable via attachments(): public function attachments(): array { return [ Pdf::view('pdfs.invoice', ['invoice' => $this->invoice]) ->name('invoice.pdf'), ]; } How it works: → PdfBuilder implements Attachable contract → File generated in memory → MIME type application/pdf added automatically → .pdf extension appended if missing No temp files. No cleanup.0,88%
  • 27 мая💸 One flag in Laravel 13.10 — and your workers stop burning money A typical queue worker runs 24/7. Actually works 3% of the time. The other 97% — idle on your AWS/GCP bill. The old option was --stop-when-empty: queue empty → worker exits. Looks perfect on paper. In practice — jobs arrive in waves with 2–3 second gaps. Worker keeps starting and stopping. Each boot is ~300ms of Laravel bootstrap. Net savings — zero. Sometimes worse. New in 13.10.0: php artisan queue:work --stop-when-empty-for=60 The worker exits only if 60 full seconds pass without a single job. One job arrives — timer resets, worker keeps going. Where it actually pays off → Serverless workers (Cloud Run, Fargate, ECS scale-to-zero) — spin up on spike, shut down clean, stop paying for idle → Autoscaling — keep-alive for 60–120 seconds of silence, then the instance dies → Cron-based workers — boot every N minutes, drain the queue, exit Small flag. Big difference on your infra bill.0,69%
  • 14 мая🔐 Laravel 13.9.0 fixes a UX wound you stopped noticing The flow nobody talks about: → user clicks "generate password" in 1Password → your form rejects it: needs a symbol, too short, whatever → user gives up and types qwerty123 Laravel 13.9.0 ships Password::toPasswordRulesString() — it converts your validation rules into the HTML passwordrules attribute (an Apple spec). Safari, 1Password and Bitwarden read it and generate a password that passes your validation on the first try. Wire it up once Declare the policy in AppServiceProvider: Password::defaults(fn () => Password::min(12)->max(64)->mixedCase()->numbers()->symbols() ); Drop it into the input: <input type="password" autocomplete="new-password" passwordrules="{{ Password::defaults()->toPasswordRulesString() }}" /> Output: minlength: 12; maxlength: 64; required: lower; required: upper; required: digit; required: special; Why it matters → One source of truth — server and browser share the policy → Generated passwords pass validation on the first try → Fewer abandoned signups → No JS copies, no duplicated regex on the frontend ⚡ Heads-up: uncompromised() is skipped — it has no equivalent in the spec. Two lines of code. Significantly less user friction.0,68%
  • 2 апр.📐 JSON:API Resources — Native Spec Support in Laravel 13 Building APIs that follow the JSON:API spec? Before: spatie/laravel-json-api or manual boilerplate. Now: built-in. Generate: php artisan make:resource PostResource --json-api Define attributes and relationships: class PostResource extends JsonApiResource { public $attributes = [ 'title', 'body', 'created_at', ]; public $relationships = [ 'author', 'comments', ]; } Return from controller: return $post->toResource(); Response follows the spec automatically: { "data": { "id": "1", "type": "posts", "attributes": { "title": "Hello World" } } } What works out of the box: → Sparse fieldsets: ?fields[posts]=title → Includes: ?include=author,comments → Links and meta → Content-Type: application/vnd.api+json → Nested relationships via dot notation For parsing incoming query params — Spatie Query Builder is still the best choice. But serialization is now native.0,63%
  • 9 янв.🔥 Property Hooks in Laravel 12: RIP getFullNameAttribute() For 10 years, we wrote accessors and prayed our IDE would understand them. PHP 8.4 changed everything. Laravel 12 embraced it. Now the logic lives directly on the property: public string $fullName { get => "{$this->first_name} {$this->last_name}"; set(string $value) => [ $this->first_name, $this->last_name ] = explode(' ', $value, 2); } Why it matters → Native type safety (no more PHPDoc hacks) → Autocomplete just works → Smaller, cleaner models → Less magic = fewer surprises Best use cases → Virtual attributes (full_name, formatted_price) → Data normalization on write → Computed fields without caching overhead Attribute::make() isn’t going anywhere. But for simple transformations — Property Hooks are cleaner and faster. Bottom line It’s 2026. Time to write models like native PHP — not Laravel 5.0,61%
  • 6 апр.🔍 UniqueConstraintViolationException Now Has Details — Laravel 13.2 Catching UniqueConstraintViolationException, but then what? Before — just a database message. Parse it yourself. Now — structured data. Before: try { User::create(['email' => 'taken@example.com']); } catch (UniqueConstraintViolationException $e) { // Which field? Parse $e->getMessage()... } After: try { User::create(['email' => 'taken@example.com']); } catch (UniqueConstraintViolationException $e) { $e->columns; // ['email'] $e->index; // 'users_email_unique' } What's available per driver: → PostgreSQL: columns ✅ index ✅ → SQLite: columns ✅ index ❌ → MySQL: columns ❌ index ✅ → SQL Server: columns ❌ index ✅ Use cases: → Human-friendly messages: "Email already taken" → Debugging composite unique constraints → Logging conflicts → Automatic duplicate handling No more parsing strings with regex.0,54%
  • 1 июн.🛡️ 5 lines in `AppServiceProvider` — and `key:generate` can't nuke your production anymore Every Laravel dev has felt this once: hit Enter on a command, and the same second realize you were in the wrong terminal. For most commands, it's a 5-second scare. For php artisan key:generate on production — it's a disaster in under a second. APP_KEY is regenerated. Then, in escalating order: → Every session invalidated — every logged-in user kicked out → Encrypted cookies become unreadable → Signed URLs go invalid → Encrypted DB columns (`encrypted` cast, `Crypt::encrypt`) turn into garbage — no way to decrypt them back Got a .env backup? That's your only lifeline. Without it — the data is gone for good. Artisan::prohibit() has been in Laravel for a while, but it didn't cover these two commands. 13.12.0 fixes that: key:generate and cache:clear can now be locked down. The fix: use Illuminate\Foundation\Console\KeyGenerateCommand; public function boot(): void { if ($this->app->isProduction()) { KeyGenerateCommand::prohibit(); } } Any accidental php artisan key:generate on production now fails with an error and does nothing. Five lines. Cheaper than restoring from a backup.0,54%
  • 18 мар.🔥 Laravel AI SDK — First-Party AI Toolkit in Laravel 13 No more third-party packages for basic AI tasks. Laravel 13 ships with an official SDK. Unified API. Any provider. Pure Laravel-way. Image generation: use Laravel\Ai\Image; $image = Image::of('Donut on a kitchen table')->generate(); Text-to-speech: use Laravel\Ai\Audio; $audio = Audio::of('Welcome to Laravel.')->generate(); Embeddings from string: use Illuminate\Support\Str; $embeddings = Str::of('Best wineries in Napa Valley')->toEmbeddings(); AI agents with tool calling: use App\Ai\Agents\SalesCoach; $response = SalesCoach::make()->prompt('Analyze this conversation...'); What's inside: → Text, images, audio, embeddings → Agents with tool calling → Vector store integrations → Provider-agnostic (OpenAI, Anthropic, etc.) Before: openai-php/client + tons of boilerplate. Now: one line, Laravel-way.0,51%
  • 5 сент. 2024 г.без подписи0,50%