[{"data":1,"prerenderedAt":475},["ShallowReactive",2],{"all-questions-laravel":3},{"beginner":4,"intermediate":167,"advanced":337},[5,14,24,33,41,48,56,65,73,82,88,96,104,110,117,125,133,139,146,152,159],{"id":6,"category":7,"question":8,"answer":9,"level":10,"tags":11},1,"Routing","What are the different ways to define routes in Laravel?","Laravel provides multiple ways to define routes for different HTTP methods and purposes.\n\n**Basic Route Definition:**\n\n```php\n\u002F\u002F routes\u002Fweb.php - For web interface\nRoute::get('\u002Fusers', [UserController::class, 'index']);\nRoute::post('\u002Fusers', [UserController::class, 'store']);\nRoute::put('\u002Fusers\u002F{id}', [UserController::class, 'update']);\nRoute::delete('\u002Fusers\u002F{id}', [UserController::class, 'destroy']);\nRoute::patch('\u002Fusers\u002F{id}', [UserController::class, 'patch']);\nRoute::options('\u002Fusers', [UserController::class, 'options']);\n```\n\n**Multiple HTTP Methods:**\n\n```php\n\u002F\u002F Match specific methods\nRoute::match(['get', 'post'], '\u002Fcontact', [ContactController::class, 'handle']);\n\n\u002F\u002F Any HTTP method\nRoute::any('\u002Fsubmit', [SubmitController::class, 'process']);\n```\n\n**Route Parameters:**\n\n```php\n\u002F\u002F Required parameters\nRoute::get('\u002Fusers\u002F{id}', function ($id) {\n    return User::find($id);\n});\n\n\u002F\u002F Optional parameters\nRoute::get('\u002Fusers\u002F{name?}', function ($name = null) {\n    return $name ?? 'All users';\n});\n\n\u002F\u002F Regular expression constraints\nRoute::get('\u002Fusers\u002F{id}', function ($id) {\n    \u002F\u002F\n})->where('id', '[0-9]+');\n\nRoute::get('\u002Fusers\u002F{name}', function ($name) {\n    \u002F\u002F\n})->where('name', '[A-Za-z]+');\n\n\u002F\u002F Multiple constraints\nRoute::get('\u002Fposts\u002F{id}\u002F{slug}', function ($id, $slug) {\n    \u002F\u002F\n})->where(['id' => '[0-9]+', 'slug' => '[A-Za-z-]+']);\n```\n\n**Global Constraints:**\n\n```php\n\u002F\u002F App\\Providers\\RouteServiceProvider\npublic function boot(): void\n{\n    Route::pattern('id', '[0-9]+');\n    Route::pattern('uuid', '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}');\n}\n```\n\n**Named Routes:**\n\n```php\nRoute::get('\u002Fuser\u002Fprofile', [ProfileController::class, 'show'])->name('profile');\n\n\u002F\u002F Generate URLs\n$url = route('profile');\n$redirect = redirect()->route('profile');\n\n\u002F\u002F With parameters\nRoute::get('\u002Fuser\u002F{id}\u002Fprofile', [ProfileController::class, 'show'])->name('profile.show');\n$url = route('profile.show', ['id' => 1]);\n```\n\n**Route Groups:**\n\n```php\n\u002F\u002F Middleware\nRoute::middleware(['auth', 'verified'])->group(function () {\n    Route::get('\u002Fdashboard', [DashboardController::class, 'index']);\n    Route::get('\u002Fsettings', [SettingsController::class, 'index']);\n});\n\n\u002F\u002F Prefix\nRoute::prefix('admin')->group(function () {\n    Route::get('\u002Fusers', [Admin\\UserController::class, 'index']);\n    Route::get('\u002Fsettings', [Admin\\SettingController::class, 'index']);\n});\n\n\u002F\u002F Subdomain\nRoute::domain('{account}.myapp.com')->group(function () {\n    Route::get('\u002Fdashboard', function ($account) {\n        return \"Dashboard for account: {$account}\";\n    });\n});\n\n\u002F\u002F Namespace\nRoute::namespace('Admin')->group(function () {\n    \u002F\u002F Controllers in App\\Http\\Controllers\\Admin namespace\n});\n```\n\n**API Routes:**\n\n```php\n\u002F\u002F routes\u002Fapi.php - automatically has \u002Fapi prefix and api middleware group\nRoute::apiResource('posts', PostController::class);\n\n\u002F\u002F API Resource routes (only index, store, show, update, destroy)\nRoute::apiResource('photos', PhotoController::class);\n```\n\n**Fallback Routes:**\n\n```php\nRoute::fallback(function () {\n    return response()->view('errors.404', [], 404);\n});\n```\n\n**Rate Limiting:**\n\n```php\nRoute::middleware(['throttle:api'])->group(function () {\n    Route::get('\u002Fapi\u002Fdata', [ApiController::class, 'data']);\n});\n\n\u002F\u002F Custom rate limiters in App\\Providers\\RouteServiceProvider\nRateLimiter::for('global', function ($job) {\n    return Limit::perMinute(1000);\n});\n```\n\n**Common Mistakes:**\n- Forgetting to clear route cache after changes (`php artisan route:clear`)\n- Defining routes in wrong order (more specific routes should come before wildcards)\n- Not using route caching in production (`php artisan route:cache`)\n\n**Security Considerations:**\n- Always validate route parameters\n- Use route model binding for automatic injection\n- Implement rate limiting on public endpoints\n\n**Follow-up Questions:**\n- How does route model binding work?\n- What's the difference between route caching and route listing?\n- How do you handle route conflicts?","beginner",[7,12,13],"HTTP Methods","Route Groups",{"id":15,"category":16,"question":17,"answer":18,"level":10,"tags":19},2,"MVC","Explain the MVC pattern and how Laravel implements it.","MVC (Model-View-Controller) is an architectural pattern that separates application concerns.\n\n**Model:**\nManages data and business logic. In Laravel, Models typically extend Eloquent.\n\n```php\nnamespace App\\Models;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass User extends Model\n{\n    \u002F\u002F Relationships\n    public function posts()\n    {\n        return $this->hasMany(Post::class);\n    }\n\n    \u002F\u002F Business logic\n    public function isAdmin(): bool\n    {\n        return $this->role === 'admin';\n    }\n\n    \u002F\u002F Accessors\n    public function getFullNameAttribute(): string\n    {\n        return \"{$this->first_name} {$this->last_name}\";\n    }\n}\n```\n\n**View:**\nHandles presentation layer. Laravel primarily uses Blade templates.\n\n```blade\n{{-- resources\u002Fviews\u002Fuser\u002Fprofile.blade.php --}}\n@extends('layouts.app')\n\n@section('content')\n    \u003Ch1>Welcome, {{ $user->full_name }}\u003C\u002Fh1>\n\n    @if($user->isAdmin())\n        \u003Cdiv class=\"admin-panel\">Admin Controls\u003C\u002Fdiv>\n    @endif\n\n    @foreach($user->posts as $post)\n        \u003Cdiv class=\"post\">\n            \u003Ch3>{{ $post->title }}\u003C\u002Fh3>\n            \u003Cp>{{ $post->content }}\u003C\u002Fp>\n        \u003C\u002Fdiv>\n    @endforeach\n@endsection\n```\n\n**Controller:**\nHandles HTTP requests, coordinates Model and View.\n\n```php\nnamespace App\\Http\\Controllers;\n\nuse App\\Models\\User;\nuse App\\Http\\Requests\\ProfileUpdateRequest;\n\nclass UserController extends Controller\n{\n    public function show($id)\n    {\n        \u002F\u002F Get data from Model\n        $user = User::with('posts')->findOrFail($id);\n\n        \u002F\u002F Pass data to View\n        return view('user.profile', ['user' => $user]);\n    }\n\n    public function update(ProfileUpdateRequest $request, $id)\n    {\n        $user = User::findOrFail($id);\n\n        \u002F\u002F Update Model\n        $user->update($request->validated());\n\n        \u002F\u002F Redirect with View\n        return redirect()->route('profile.show', $user->id)\n            ->with('success', 'Profile updated!');\n    }\n}\n```\n\n**How Laravel Implements MVC:**\n\n1. **Request Flow:**\n   - HTTP Request → Route → Controller → Model → View → Response\n\n2. **Model Layer:**\n   - Eloquent ORM for database interaction\n   - Relationships, scopes, accessors, mutators\n   - Events, observers, factories\n\n3. **View Layer:**\n   - Blade templating engine\n   - View composers and creators\n   - Partial views and components\n\n4. **Controller Layer:**\n   - Resource controllers for RESTful actions\n   - Form request validation\n   - Middleware for request filtering\n   - Dependency injection\n\n**Additional Laravel Components:**\n\n```php\n\u002F\u002F Service Layer (beyond MVC)\nclass UserService\n{\n    public function createUser(array $data): User\n    {\n        \u002F\u002F Complex business logic spanning multiple models\n        DB::transaction(function () use ($data) {\n            $user = User::create($data);\n            $user->profile()->create($data['profile']);\n            event(new UserCreated($user));\n            return $user;\n        });\n    }\n}\n```\n\n**Best Practices:**\n- Keep controllers thin (delegate business logic to models\u002Fservices)\n- Use form requests for validation\n- Leverage route model binding\n- Implement repository pattern for complex queries\n- Use view composers for shared view data\n\n**Common Mistakes:**\n- Fat controllers with business logic\n- Database queries in views\n- Direct model manipulation in routes\n- Ignoring eager loading (N+1 problem)\n\n**Performance Considerations:**\n- Eager load relationships to prevent N+1 queries\n- Cache expensive queries\n- Use pagination for large datasets\n\n**Security Considerations:**\n- Always use mass assignment protection (`$fillable` or `$guarded`)\n- Validate all user input\n- Escape output in views (Blade does this automatically)\n\n**Follow-up Questions:**\n- How does Laravel's request lifecycle work?\n- What's the difference between a controller and a service class?\n- How do you handle complex business logic without fat models?",[16,20,21,22,23],"Architecture","Models","Views","Controllers",{"id":25,"category":26,"question":27,"answer":28,"level":10,"tags":29},3,"Artisan","What are the most useful Artisan commands and how to create custom commands?","Artisan is Laravel's command-line interface that provides helpful commands for development.\n\n**Essential Built-in Commands:**\n\n```bash\n# Development\nphp artisan serve              # Start development server\nphp artisan tinker             # Interactive REPL\nphp artisan make:model User    # Create model\nphp artisan make:controller UserController\nphp artisan make:migration create_users_table\nphp artisan make:seeder UserSeeder\nphp artisan make:factory UserFactory\nphp artisan make:middleware CustomMiddleware\nphp artisan make:event OrderPlaced\nphp artisan make:listener SendOrderNotification\nphp artisan make:job ProcessOrder\nphp artisan make:mail OrderShipped\nphp artisan make:notification OrderPaid\nphp artisan make:policy PostPolicy\nphp artisan make:rule Uppercase\nphp artisan make:scope ActiveScope\n\n# Database\nphp artisan migrate              # Run migrations\nphp artisan migrate:fresh        # Drop tables and re-run migrations\nphp artisan migrate:rollback     # Rollback last migration\nphp artisan db:seed              # Run seeders\nphp artisan migrate:refresh      # Rollback and re-run all migrations\nphp artisan migrate:status       # Show migration status\n\n# Caching\nphp artisan cache:clear          # Clear application cache\nphp artisan config:clear         # Clear config cache\nphp artisan route:clear          # Clear route cache\nphp artisan view:clear           # Clear compiled views\nphp artisan optimize:clear       # Clear all caches\nphp artisan config:cache         # Cache configuration\nphp artisan route:cache          # Cache routes\nphp artisan event:cache          # Cache events\n\n# Debugging\nphp artisan route:list           # List all routes\nphp artisan vendor:publish       # Publish vendor files\nphp artisan about                # Display application details\nphp artisan env                  # Show current environment\n\n# Queue\nphp artisan queue:work           # Process queue jobs\nphp artisan queue:failed         # List failed jobs\nphp artisan queue:retry all      # Retry failed jobs\nphp artisan queue:flush          # Delete all failed jobs\n\n# Scheduling\nphp artisan schedule:list        # List scheduled tasks\nphp artisan schedule:run         # Run scheduled tasks\n\n# Production\nphp artisan optimize             # Cache all configurations\nphp artisan down                 # Put application in maintenance mode\nphp artisan up                   # Bring application out of maintenance mode\n```\n\n**Creating Custom Commands:**\n\n```bash\nphp artisan make:command SendEmails\n```\n\n```php\nnamespace App\\Console\\Commands;\n\nuse Illuminate\\Console\\Command;\nuse App\\Services\\EmailService;\n\nclass SendEmails extends Command\n{\n    \u002F**\n     * The name and signature of the console command.\n     * @var string\n     *\u002F\n    protected $signature = 'emails:send\n                            {users? : Specific user ID or \"all\"}\n                            {--queue : Send emails using queue}\n                            {--limit=100 : Maximum emails to send}\n                            {--type=newsletter : Type of email to send}';\n\n    \u002F**\n     * The console command description.\n     * @var string\n     *\u002F\n    protected $description = 'Send emails to users';\n\n    \u002F**\n     * Execute the console command.\n     *\u002F\n    public function handle(EmailService $emailService)\n    {\n        $this->info('Starting email sending process...');\n\n        \u002F\u002F Get arguments\n        $users = $this->argument('users');\n        $queue = $this->option('queue');\n        $limit = $this->option('limit');\n        $type = $this->option('type');\n\n        \u002F\u002F Progress bar\n        $bar = $this->output->createProgressBar($limit);\n\n        \u002F\u002F Ask for confirmation\n        if ($this->confirm('Do you wish to continue sending emails?')) {\n            \u002F\u002F Table output\n            $this->table(\n                ['User ID', 'Email', 'Status'],\n                $this->getEmailStatus()\n            );\n\n            \u002F\u002F Ask for input\n            $batchSize = $this->ask('What batch size would you like?', 50);\n\n            \u002F\u002F Secret input\n            $password = $this->secret('Enter the API password');\n\n            \u002F\u002F Choice\n            $provider = $this->choice(\n                'Which email provider?',\n                ['sendgrid', 'mailgun', 'ses'],\n                0\n            );\n\n            $bar->finish();\n            $this->newLine();\n            $this->info('Emails sent successfully!');\n        }\n    }\n\n    private function getEmailStatus(): array\n    {\n        return [\n            [1, 'user1@example.com', 'Sent'],\n            [2, 'user2@example.com', 'Pending'],\n        ];\n    }\n}\n```\n\n**Command Signatures Advanced:**\n\n```php\n\u002F\u002F Arrays\nprotected $signature = 'emails:send {users*}';\n\u002F\u002F Usage: php artisan emails:send 1 2 3 4\n\n\u002F\u002F Optional with default\nprotected $signature = 'emails:send {users=all}';\n\n\u002F\u002F Option with shortcut\nprotected $signature = 'emails:send {--Q|queue}';\n\n\u002F\u002F Option with value\nprotected $signature = 'emails:send {--limit=100}';\n\n\u002F\u002F Option array\nprotected $signature = 'emails:send {--id=*}';\n\u002F\u002F Usage: php artisan emails:send --id=1 --id=2\n```\n\n**Scheduled Commands:**\n\n```php\n\u002F\u002F bootstrap\u002Fapp.php (Laravel 11+)\n->withSchedule(function ($schedule) {\n    $schedule->command('emails:send --queue')\n             ->daily()\n             ->at('08:00')\n             ->timezone('America\u002FNew_York')\n             ->emailOutputTo('admin@example.com');\n\n    $schedule->exec('node script.js')\n             ->everyMinute()\n             ->appendOutputTo(storage_path('logs\u002Fnode.log'));\n})\n```\n\n**Command Testing:**\n\n```php\npublic function test_command_sends_emails()\n{\n    $this->artisan('emails:send', ['users' => 1, '--queue' => true])\n         ->expectsOutput('Starting email sending process...')\n         ->expectsQuestion('What batch size would you like?', 50)\n         ->expectsChoice('Which email provider?', 'sendgrid', ['sendgrid', 'mailgun'])\n         ->expectsTable(['User ID', 'Email', 'Status'], [...]])\n         ->assertExitCode(0);\n}\n```\n\n**Common Mistakes:**\n- Not handling command failures properly\n- Long-running commands blocking other operations\n- Not using progress bars for lengthy operations\n- Hardcoding paths instead of using Laravel helpers\n\n**Best Practices:**\n- Use dependency injection in commands\n- Implement proper error handling and logging\n- Use `$this->error()` for errors and `$this->warn()` for warnings\n- Make commands idempotent when possible\n- Use `--force` flags for destructive operations\n\n**Performance Considerations:**\n- Use chunking for large datasets\n- Implement queue for heavy operations\n- Use `$this->withProgressBar()` for visual feedback\n\n**Follow-up Questions:**\n- How do you schedule commands in production?\n- How do you handle command dependencies?\n- What's the difference between `queue:work` and `queue:listen`?",[26,30,31,32],"CLI","Commands","Scheduling",{"id":34,"category":35,"question":36,"answer":37,"level":10,"tags":38},4,"Middleware","What is Middleware and how do you create custom middleware?","Middleware provides a mechanism for filtering HTTP requests entering your application.\n\n**Understanding Middleware:**\n\nMiddleware acts as a bridge between a request and the application. It can inspect, modify, or reject requests before they reach controllers, and modify responses before they're sent to clients.\n\n**Creating Custom Middleware:**\n\n```bash\nphp artisan make:middleware CheckUserRole\n```\n\n```php\nnamespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Http\\Response;\n\nclass CheckUserRole\n{\n    \u002F**\n     * Handle an incoming request.\n     *\n     * @param  \\Closure(\\Illuminate\\Http\\Request): (\\Illuminate\\Http\\Response)  $next\n     *\u002F\n    public function handle(Request $request, Closure $next, string $role): Response\n    {\n        \u002F\u002F Before middleware - runs before request reaches controller\n        if (! $request->user() || ! $request->user()->hasRole($role)) {\n            \u002F\u002F Reject the request\n            abort(403, 'Unauthorized access.');\n        }\n\n        \u002F\u002F Allow request to proceed to next middleware\u002Fcontroller\n        $response = $next($request);\n\n        \u002F\u002F After middleware - runs after controller returns response\n        $response->headers->set('X-User-Role', $role);\n\n        return $response;\n    }\n}\n```\n\n**Registering Middleware (Laravel 11+):**\n\n```php\n\u002F\u002F bootstrap\u002Fapp.php\nuse Illuminate\\Foundation\\Configuration\\Middleware;\n\nreturn Application::configure(basePath: dirname(__DIR__))\n    ->withMiddleware(function (Middleware $middleware) {\n        \u002F\u002F Global middleware (runs on every request)\n        $middleware->append([\n            \\App\\Http\\Middleware\\LogRequests::class,\n            \\App\\Http\\Middleware\\MaintenanceMode::class,\n        ]);\n\n        \u002F\u002F Add to web group\n        $middleware->web(append: [\n            \\App\\Http\\Middleware\\VerifyCsrfToken::class,\n        ]);\n\n        \u002F\u002F Add to api group\n        $middleware->api(prepend: [\n            \\App\\Http\\Middleware\\ForceJsonResponse::class,\n        ]);\n\n        \u002F\u002F Register aliases for route middleware\n        $middleware->alias([\n            'auth' => \\Illuminate\\Auth\\Middleware\\Authenticate::class,\n            'role' => \\App\\Http\\Middleware\\CheckUserRole::class,\n            'throttle' => \\Illuminate\\Routing\\Middleware\\ThrottleRequests::class,\n        ]);\n\n        \u002F\u002F Priority ordering\n        $middleware->priority([\n            \\Illuminate\\Foundation\\Http\\Middleware\\HandlePrecognitiveRequests::class,\n            \\Illuminate\\Cookie\\Middleware\\EncryptCookies::class,\n        ]);\n    })\n    ->create();\n```\n\n**Using Middleware in Routes:**\n\n```php\n\u002F\u002F Single middleware\nRoute::get('\u002Fadmin', [AdminController::class, 'index'])\n    ->middleware('role:admin');\n\n\u002F\u002F Multiple middleware\nRoute::get('\u002Fdashboard', [DashboardController::class, 'index'])\n    ->middleware(['auth', 'verified', 'role:admin']);\n\n\u002F\u002F Middleware groups\nRoute::middleware(['web', 'auth'])->group(function () {\n    Route::get('\u002Fprofile', [ProfileController::class, 'index']);\n    Route::get('\u002Fsettings', [SettingsController::class, 'index']);\n});\n\n\u002F\u002F Excluding middleware\nRoute::get('\u002Fpublic-page', [PageController::class, 'show'])\n    ->withoutMiddleware(['auth']);\n```\n\n**Before vs After Middleware:**\n\n```php\nclass RequestLoggerMiddleware\n{\n    public function handle(Request $request, Closure $next)\n    {\n        \u002F\u002F BEFORE: Log request before processing\n        Log::info('Request received', [\n            'method' => $request->method(),\n            'url' => $request->fullUrl(),\n            'ip' => $request->ip(),\n        ]);\n\n        $startTime = microtime(true);\n\n        $response = $next($request);\n\n        \u002F\u002F AFTER: Log response after processing\n        $duration = microtime(true) - $startTime;\n\n        Log::info('Response sent', [\n            'status' => $response->getStatusCode(),\n            'duration' => round($duration, 2) . 'ms',\n        ]);\n\n        return $response;\n    }\n}\n```\n\n**Terminable Middleware:**\n\n```php\nclass SendWebhookMiddleware\n{\n    public function handle(Request $request, Closure $next)\n    {\n        return $next($request);\n    }\n\n    \u002F**\n     * Called after response is sent to browser\n     * Good for slow operations that don't affect response\n     *\u002F\n    public function terminate(Request $request, Response $response): void\n    {\n        \u002F\u002F Send analytics, webhooks, clean up, etc.\n        if ($response->getStatusCode() === 200) {\n            Webhook::dispatch('request.success', [\n                'url' => $request->url(),\n                'user_id' => $request->user()?->id,\n            ]);\n        }\n    }\n}\n```\n\n**Middleware Parameters:**\n\n```php\nclass ThrottleByRoleMiddleware\n{\n    public function handle(Request $request, Closure $next, $maxAttempts, $decayMinutes = 1)\n    {\n        $key = 'throttle:' . $request->user()->role . ':' . $request->ip();\n\n        if (RateLimiter::tooManyAttempts($key, $maxAttempts)) {\n            return response('Too many attempts.', 429);\n        }\n\n        RateLimiter::hit($key, $decayMinutes * 60);\n\n        return $next($request);\n    }\n}\n\n\u002F\u002F Route usage\nRoute::post('\u002Fapi\u002Fdata', [ApiController::class, 'store'])\n    ->middleware('throttle.role:100,5'); \u002F\u002F 100 attempts per 5 minutes\n```\n\n**Practical Examples:**\n\n```php\n\u002F\u002F CORS Middleware\nclass CorsMiddleware\n{\n    public function handle(Request $request, Closure $next)\n    {\n        $response = $next($request);\n\n        $response->headers->set('Access-Control-Allow-Origin', env('CORS_ALLOWED_ORIGINS', '*'));\n        $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');\n        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');\n\n        if ($request->getMethod() === 'OPTIONS') {\n            return response('', 200)->withHeaders($response->headers->all());\n        }\n\n        return $response;\n    }\n}\n\n\u002F\u002F Maintenance Mode Middleware\nclass MaintenanceModeMiddleware\n{\n    public function handle(Request $request, Closure $next)\n    {\n        if (app()->isDownForMaintenance() && !$request->has('secret')) {\n            return response('Under maintenance', 503);\n        }\n\n        return $next($request);\n    }\n}\n```\n\n**Common Mistakes:**\n- Forgetting to call `$next($request)`\n- Heavy operations in middleware (use terminable middleware instead)\n- Not handling middleware order dependencies\n- Returning incorrect response types\n\n**Performance Considerations:**\n- Middleware runs on every request, keep them lightweight\n- Cache expensive checks\n- Use terminable middleware for non-critical operations\n- Order middleware by importance (cheap checks first)\n\n**Security Considerations:**\n- Validate user permissions early\n- Implement rate limiting\n- Sanitize request data\n- Log suspicious activities\n\n**Testing Middleware:**\n\n```php\npublic function test_role_middleware_blocks_unauthorized()\n{\n    $user = User::factory()->create(['role' => 'user']);\n\n    $response = $this->actingAs($user)\n        ->get('\u002Fadmin\u002Fdashboard');\n\n    $response->assertStatus(403);\n}\n```\n\n**Follow-up Questions:**\n- What's the difference between global and route middleware?\n- How does middleware priority work?\n- Can middleware modify responses?\n- What happens if middleware throws an exception?",[35,39,40],"HTTP","Request Lifecycle",{"id":42,"category":43,"question":44,"answer":45,"level":10,"tags":46},5,"Blade","What are the key features of Laravel Blade templating engine?","Blade is Laravel's powerful templating engine that provides elegant syntax for creating views.\n\n**Template Inheritance:**\n\n```blade\n{{-- layouts\u002Fapp.blade.php --}}\n\u003C!DOCTYPE html>\n\u003Chtml>\n\u003Chead>\n    \u003Ctitle>@yield('title', 'Default Title')\u003C\u002Ftitle>\n    @stack('styles')\n\u003C\u002Fhead>\n\u003Cbody>\n    @include('partials.navbar')\n\n    \u003Cdiv class=\"container\">\n        @yield('content')\n    \u003C\u002Fdiv>\n\n    @stack('scripts')\n\u003C\u002Fbody>\n\u003C\u002Fhtml>\n\n{{-- pages\u002Fhome.blade.php --}}\n@extends('layouts.app')\n\n@section('title', 'Home Page')\n\n@push('styles')\n    \u003Clink href=\"\u002Fcss\u002Fhome.css\" rel=\"stylesheet\">\n@endpush\n\n@section('content')\n    \u003Ch1>Welcome\u003C\u002Fh1>\n\n    @parent {{-- Include parent content --}}\n@stop\n\n@push('scripts')\n    \u003Cscript src=\"\u002Fjs\u002Fhome.js\">\u003C\u002Fscript>\n@endpush\n```\n\n**Displaying Data:**\n\n```blade\n{{-- Automatic HTML escaping --}}\n\u003Ch1>{{ $user->name }}\u003C\u002Fh1>\n\u003Cp>{{ $post->content }}\u003C\u002Fp>\n\n{{-- Unescaped data (be careful with user input) --}}\n\u003Cdiv>{!! $htmlContent !!}\u003C\u002Fdiv>\n\n{{-- Check existence with default --}}\n\u003Cp>{{ $user->bio ?? 'No bio provided' }}\u003C\u002Fp>\n\n{{-- JSON data --}}\n\u003Cscript>\n    var user = @json($user);\n    var settings = @json(['theme' => 'dark', 'lang' => 'en']);\n\u003C\u002Fscript>\n```\n\n**Control Structures:**\n\n```blade\n{{-- Conditionals --}}\n@if($user->isAdmin())\n    \u003Cdiv class=\"admin-panel\">Admin Controls\u003C\u002Fdiv>\n@elseif($user->isModerator())\n    \u003Cdiv class=\"mod-panel\">Mod Controls\u003C\u002Fdiv>\n@else\n    \u003Cdiv>Regular User View\u003C\u002Fdiv>\n@endif\n\n@unless($user->isBanned())\n    \u003Cp>User is active\u003C\u002Fp>\n@endunless\n\n@isset($records)\n    \u003Cp>Records found: {{ count($records) }}\u003C\u002Fp>\n@endisset\n\n@empty($records)\n    \u003Cp>No records found\u003C\u002Fp>\n@endempty\n\n@auth\n    \u003Cp>Welcome back, {{ auth()->user()->name }}\u003C\u002Fp>\n@endauth\n\n@guest\n    \u003Cp>Please log in\u003C\u002Fp>\n@endguest\n\n@production\n    {{-- Only in production --}}\n@else\n    {{-- Development code --}}\n@endproduction\n\n{{-- Loops --}}\n@for($i = 0; $i \u003C 10; $i++)\n    \u003Cp>Iteration: {{ $i }}\u003C\u002Fp>\n@endfor\n\n@foreach($users as $user)\n    @if($loop->first)\n        \u003Cdiv class=\"first-item\">\n    @endif\n\n    \u003Cp>{{ $user->name }}\u003C\u002Fp>\n\n    @if($loop->last)\n        \u003C\u002Fdiv>\n    @endif\n@endforeach\n\n@forelse($posts as $post)\n    \u003Cdiv class=\"post\">\n        \u003Ch3>{{ $post->title }}\u003C\u002Fh3>\n        \u003Cp>{{ $post->excerpt }}\u003C\u002Fp>\n    \u003C\u002Fdiv>\n@empty\n    \u003Cp>No posts found\u003C\u002Fp>\n@endforelse\n\n@while($condition)\n    \u003Cp>Looping...\u003C\u002Fp>\n@endwhile\n\n{{-- Loop variables --}}\n@foreach($items as $item)\n    \u003Cp>\n        Index: {{ $loop->index }} |\n        Iteration: {{ $loop->iteration }} |\n        Remaining: {{ $loop->remaining }} |\n        Count: {{ $loop->count }} |\n        First: {{ $loop->first ? 'Yes' : 'No' }} |\n        Last: {{ $loop->last ? 'Yes' : 'No' }} |\n        Depth: {{ $loop->depth }}\n    \u003C\u002Fp>\n@endforeach\n```\n\n**Components:**\n\n```blade\n{{-- app\u002FView\u002FComponents\u002FAlert.php --}}\nclass Alert extends Component\n{\n    public function __construct(\n        public string $type = 'info',\n        public ?string $message = null\n    ) {}\n\n    public function render()\n    {\n        return view('components.alert');\n    }\n}\n\n{{-- resources\u002Fviews\u002Fcomponents\u002Falert.blade.php --}}\n\u003Cdiv class=\"alert alert-{{ $type }}\">\n    @if($slot->isEmpty())\n        {{ $message }}\n    @else\n        {{ $slot }}\n    @endif\n\u003C\u002Fdiv>\n\n{{-- Usage --}}\n\u003Cx-alert type=\"success\" message=\"Operation successful!\" \u002F>\n\n\u003Cx-alert type=\"warning\">\n    \u003Cstrong>Warning!\u003C\u002Fstrong> Please check your input.\n\u003C\u002Fx-alert>\n\n{{-- Anonymous components --}}\n{{-- resources\u002Fviews\u002Fcomponents\u002Fbutton.blade.php --}}\n\u003Cbutton {{ $attributes->merge(['class' => 'btn btn-primary']) }}>\n    {{ $slot }}\n\u003C\u002Fbutton>\n\n\u003Cx-button type=\"submit\" class=\"large\">Save\u003C\u002Fx-button>\n```\n\n**Includes and Subviews:**\n\n```blade\n{{-- Include with data --}}\n@include('partials.header', ['title' => 'My Page'])\n\n{{-- Include if exists --}}\n@includeIf('partials.custom-header')\n\n{{-- Include based on condition --}}\n@includeWhen($user->isAdmin(), 'admin.menu')\n\n{{-- Include first existing --}}\n@includeFirst(['custom.header', 'default.header'])\n\n{{-- Each directive --}}\n@each('partials.user', $users, 'user', 'partials.empty')\n```\n\n**Stacks and Prepends:**\n\n```blade\n{{-- Layout --}}\n\u003Chead>\n    @stack('styles')\n    @stack('scripts')\n\u003C\u002Fhead>\n\n{{-- Child view --}}\n@push('styles')\n    \u003Clink href=\"\u002Fcss\u002Fpage.css\" rel=\"stylesheet\">\n@endpush\n\n@prepend('scripts')\n    \u003Cscript src=\"\u002Fjs\u002Fjquery.js\">\u003C\u002Fscript>\n@endprepend\n\n@pushOnce('styles')\n    \u003Clink href=\"\u002Fcss\u002Funique.css\" rel=\"stylesheet\">\n@endPushOnce\n```\n\n**Custom Directives:**\n\n```php\n\u002F\u002F AppServiceProvider\nuse Illuminate\\Support\\Facades\\Blade;\n\npublic function boot()\n{\n    Blade::directive('datetime', function ($expression) {\n        return \"\u003C?php echo ($expression)->format('Y-m-d H:i:s'); ?>\";\n    });\n\n    Blade::if('admin', function () {\n        return auth()->check() && auth()->user()->isAdmin();\n    });\n}\n\n\u002F\u002F Usage\n@datetime($user->created_at)\n\n@admin\n    \u003Cdiv>Admin content\u003C\u002Fdiv>\n@endadmin\n```\n\n**Performance Optimization:**\n\n```blade\n{{-- Cache views (automatic in production) --}}\nphp artisan view:cache\nphp artisan view:clear\n\n{{-- Avoid heavy logic in views --}}\n{{-- Bad --}}\n@foreach(User::where('active', true)->get() as $user)\n\n{{-- Good --}}\n@foreach($activeUsers as $user)\n\n{{-- Use eager loading --}}\n@foreach($posts->load('comments') as $post)\n```\n\n**Security Features:**\n\n```blade\n{{-- Automatic XSS protection with {{ }} --}}\n\u003Cscript>var name = '{{ $userInput }}';\u003C\u002Fscript> {{-- Escaped --}}\n\n{{-- CSRF protection --}}\n\u003Cform method=\"POST\">\n    @csrf\n\u003C\u002Fform>\n\n{{-- Method spoofing --}}\n@method('PUT')\n\n{{-- Error handling --}}\n@error('email')\n    \u003Cdiv class=\"error\">{{ $message }}\u003C\u002Fdiv>\n@enderror\n```\n\n**Common Mistakes:**\n- Using `{!! !!}` with user input (XSS risk)\n- Putting complex logic in views\n- Forgetting to use `@csrf` in forms\n- Not using eager loading causing N+1 queries\n\n**Best Practices:**\n- Keep views focused on presentation only\n- Use view composers for shared data\n- Leverage components for reusable UI elements\n- Use sections and layouts to avoid duplication\n\n**Follow-up Questions:**\n- What's the difference between `@yield` and `@section`?\n- How do you pass data from components to layouts?\n- Can you use Blade outside Laravel?",[43,47,22],"Templating",{"id":49,"category":50,"question":51,"answer":52,"level":10,"tags":53},6,"Migrations","How do you create and manage database migrations in Laravel?","Migrations are version control for your database schema, allowing you to modify and share the database schema across team members.\n\n**Creating Migrations:**\n\n```bash\n# Create migration\nphp artisan make:migration create_users_table\nphp artisan make:migration add_avatar_to_users_table\nphp artisan make:migration create_products_table --create=products\nphp artisan make:migration add_foreign_key_to_posts_table --table=posts\n```\n\n**Migration Structure:**\n\n```php\nuse Illuminate\\Database\\Migrations\\Migration;\nuse Illuminate\\Database\\Schema\\Blueprint;\nuse Illuminate\\Support\\Facades\\Schema;\n\nreturn new class extends Migration\n{\n    \u002F**\n     * Run the migrations.\n     *\u002F\n    public function up(): void\n    {\n        Schema::create('users', function (Blueprint $table) {\n            \u002F\u002F Column types\n            $table->id(); \u002F\u002F Big integer auto-increment primary key\n            $table->uuid('uuid')->unique();\n            $table->string('name', 100);\n            $table->string('email')->unique();\n            $table->timestamp('email_verified_at')->nullable();\n            $table->string('password');\n            $table->rememberToken();\n            $table->enum('role', ['admin', 'user', 'moderator'])->default('user');\n            $table->json('meta')->nullable();\n            $table->boolean('is_active')->default(true);\n            $table->integer('login_count')->default(0);\n            $table->unsignedBigInteger('created_by')->nullable();\n\n            \u002F\u002F Indexes\n            $table->index('email');\n            $table->index(['role', 'is_active']);\n            $table->fullText('bio');\n\n            \u002F\u002F Foreign keys\n            $table->foreign('created_by')\n                  ->references('id')\n                  ->on('users')\n                  ->onDelete('set null');\n\n            \u002F\u002F Timestamps\n            $table->timestamps(); \u002F\u002F created_at, updated_at\n            $table->softDeletes(); \u002F\u002F deleted_at\n\n            \u002F\u002F Spatial data (PostGIS)\n            $table->point('location')->spatialIndex();\n        });\n    }\n\n    \u002F**\n     * Reverse the migrations.\n     *\u002F\n    public function down(): void\n    {\n        Schema::dropIfExists('users');\n    }\n};\n```\n\n**All Column Types:**\n\n```php\n$table->id();                    \u002F\u002F bigIncrements('id')\n$table->bigIncrements('id');     \u002F\u002F Unsigned big integer auto-increment\n$table->unsignedBigInteger('user_id');\n$table->increments('id');        \u002F\u002F Auto-incrementing UNSIGNED INTEGER\n$table->smallIncrements('id');   \u002F\u002F Auto-incrementing UNSIGNED SMALLINT\n$table->tinyIncrements('id');    \u002F\u002F Auto-incrementing UNSIGNED TINYINT\n\n\u002F\u002F Numbers\n$table->integer('votes');\n$table->tinyInteger('status');\n$table->smallInteger('priority');\n$table->mediumInteger('position');\n$table->bigInteger('large_number');\n$table->unsignedInteger('count');\n$table->float('amount', 8, 2);\n$table->double('price', 15, 8);\n$table->decimal('balance', 10, 2);\n\n\u002F\u002F Strings\n$table->string('name', 100);\n$table->char('code', 3);\n$table->text('description');\n$table->mediumText('content');\n$table->longText('large_content');\n\n\u002F\u002F Date\u002FTime\n$table->date('birth_date');\n$table->dateTime('started_at');\n$table->dateTimeTz('created_at');\n$table->time('sunrise');\n$table->timeTz('sunset');\n$table->timestamp('published_at');\n$table->timestampTz('logged_at');\n$table->year('graduation_year');\n\n\u002F\u002F Other\n$table->boolean('is_active');\n$table->enum('status', ['draft', 'published', 'archived']);\n$table->json('options');\n$table->jsonb('settings');\n$table->binary('photo');\n$table->ipAddress('ip_address');\n$table->macAddress('mac');\n$table->geometry('positions');\n$table->geometryCollection('collections');\n$table->point('location');\n```\n\n**Modifying Existing Tables:**\n\n```php\n\u002F\u002F Add columns\nSchema::table('users', function (Blueprint $table) {\n    $table->string('phone')->after('email');\n    $table->string('avatar')->nullable();\n    $table->softDeletes();\n});\n\n\u002F\u002F Modify columns (requires doctrine\u002Fdbal)\nSchema::table('users', function (Blueprint $table) {\n    $table->string('name', 150)->change();\n    $table->string('email')->nullable()->change();\n});\n\n\u002F\u002F Rename columns\nSchema::table('users', function (Blueprint $table) {\n    $table->renameColumn('username', 'name');\n});\n\n\u002F\u002F Drop columns\nSchema::table('users', function (Blueprint $table) {\n    $table->dropColumn(['phone', 'avatar']);\n    $table->dropSoftDeletes();\n});\n\n\u002F\u002F Indexes\nSchema::table('users', function (Blueprint $table) {\n    $table->index('email');\n    $table->unique(['email', 'role']);\n    $table->dropIndex(['email']);\n    $table->dropUnique(['email', 'role']);\n});\n\n\u002F\u002F Foreign keys\nSchema::table('posts', function (Blueprint $table) {\n    $table->foreignId('user_id')->constrained()->onDelete('cascade');\n    $table->foreignId('category_id')->constrained();\n    $table->dropForeign(['user_id']);\n});\n```\n\n**Running Migrations:**\n\n```bash\n# Run all pending migrations\nphp artisan migrate\n\n# Run migrations and seed\nphp artisan migrate --seed\n\n# Rollback last batch\nphp artisan migrate:rollback\n\n# Rollback multiple batches\nphp artisan migrate:rollback --step=3\n\n# Reset all migrations\nphp artisan migrate:reset\n\n# Rollback and re-run all migrations\nphp artisan migrate:refresh\nphp artisan migrate:refresh --seed\n\n# Drop all tables and re-run migrations\nphp artisan migrate:fresh\nphp artisan migrate:fresh --seed\n\n# Check migration status\nphp artisan migrate:status\n\n# Pretend run (see SQL without executing)\nphp artisan migrate --pretend\n```\n\n**Migration Squashing:**\n\n```bash\n# Squash migrations into a single SQL file\nphp artisan schema:dump\n\n# Dump with pruning\nphp artisan schema:dump --prune\n```\n\n**Foreign Key Constraints:**\n\n```php\n\u002F\u002F On delete options\n$table->foreignId('user_id')\n      ->constrained()\n      ->onDelete('cascade');  \u002F\u002F Also: restrict, set null, no action\n\n\u002F\u002F Custom foreign key name\n$table->foreign('user_id')\n      ->references('id')\n      ->on('users')\n      ->onDelete('cascade');\n\n\u002F\u002F Disable foreign key checks (for testing)\nSchema::disableForeignKeyConstraints();\n\u002F\u002F operations\nSchema::enableForeignKeyConstraints();\n```\n\n**Best Practices:**\n\n```php\n\u002F\u002F Use indexes for foreign keys\nSchema::create('posts', function (Blueprint $table) {\n    $table->id();\n    $table->foreignId('user_id')->constrained()->index();\n    $table->string('title');\n    $table->index(['user_id', 'created_at']); \u002F\u002F Composite index\n});\n\n\u002F\u002F Use appropriate column sizes\n$table->string('name', 100); \u002F\u002F Not 255\n$table->string('country_code', 2);\n\n\u002F\u002F Use nullable sparingly\n$table->string('middle_name')->nullable(); \u002F\u002F Only if truly optional\n\n\u002F\u002F Always implement down method\npublic function down()\n{\n    Schema::dropIfExists('users');\n}\n```\n\n**Common Mistakes:**\n- Not having a down method for rollbacks\n- Adding indexes after inserting data (performance hit)\n- Using `nullable()` on columns that should be required\n- Not using foreign key constraints for data integrity\n- Forgetting to install doctrine\u002Fdbal for column modifications\n\n**Performance Considerations:**\n- Index columns used in WHERE, JOIN, and ORDER BY\n- Avoid indexes on columns with low cardinality\n- Use `--pretend` to review SQL before production\n- Run migrations during maintenance windows for large tables\n\n**Security Considerations:**\n- Never store sensitive data in column names\n- Use appropriate column types for data validation\n- Implement soft deletes for audit trails\n\n**Follow-up Questions:**\n- How do you handle migrations in a team environment?\n- What happens if a migration fails mid-way?\n- How do you seed data after migrations?\n- Can you use raw SQL in migrations?",[50,54,55],"Database","Schema",{"id":57,"category":58,"question":59,"answer":60,"level":10,"tags":61},7,"Eloquent Basics","What is Eloquent ORM and how do you use basic CRUD operations?","Eloquent is Laravel's ORM (Object-Relational Mapping) that provides an active record implementation for database interaction.\n\n**Model Definition:**\n\n```php\nnamespace App\\Models;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\n\nclass User extends Model\n{\n    use HasFactory;\n\n    \u002F\u002F Table name (optional, default is plural snake case)\n    protected $table = 'users';\n\n    \u002F\u002F Primary key (optional, default is 'id')\n    protected $primaryKey = 'id';\n\n    \u002F\u002F Key type (optional)\n    protected $keyType = 'int';\n\n    \u002F\u002F Incrementing (optional)\n    public $incrementing = true;\n\n    \u002F\u002F Timestamps (optional)\n    public $timestamps = true;\n\n    \u002F\u002F Mass assignment protection\n    protected $fillable = [\n        'name', 'email', 'password',\n    ];\n\n    \u002F\u002F Or use guarded\n    protected $guarded = ['id', 'created_at'];\n\n    \u002F\u002F Hidden attributes for serialization\n    protected $hidden = ['password', 'remember_token'];\n\n    \u002F\u002F Visible attributes\n    protected $visible = ['name', 'email'];\n\n    \u002F\u002F Cast attributes\n    protected $casts = [\n        'email_verified_at' => 'datetime',\n        'is_admin' => 'boolean',\n        'settings' => 'array',\n        'metadata' => 'json',\n        'id' => 'integer',\n    ];\n\n    \u002F\u002F Date fields\n    protected $dates = [\n        'created_at', 'updated_at', 'deleted_at',\n    ];\n\n    \u002F\u002F Date format\n    protected $dateFormat = 'Y-m-d H:i:s';\n}\n```\n\n**Create (Insert):**\n\n```php\n\u002F\u002F Method 1: Using create()\n$user = User::create([\n    'name' => 'John Doe',\n    'email' => 'john@example.com',\n    'password' => bcrypt('password123'),\n]);\n\n\u002F\u002F Method 2: Using new instance\n$user = new User();\n$user->name = 'Jane Doe';\n$user->email = 'jane@example.com';\n$user->password = bcrypt('password456');\n$user->save();\n\n\u002F\u002F Method 3: Using make() (doesn't persist)\n$user = User::make([\n    'name' => 'Temporary User',\n    'email' => 'temp@example.com',\n]);\n\n\u002F\u002F Method 4: First or create\n$user = User::firstOrCreate(\n    ['email' => 'john@example.com'], \u002F\u002F Search criteria\n    ['name' => 'John Doe', 'password' => bcrypt('pass')] \u002F\u002F Additional data\n);\n\n\u002F\u002F Method 5: First or new\n$user = User::firstOrNew(\n    ['email' => 'unknown@example.com'],\n    ['name' => 'Unknown User']\n);\n\u002F\u002F $user->exists = false, need to call save()\n\n\u002F\u002F Method 6: Update or create\n$user = User::updateOrCreate(\n    ['email' => 'john@example.com'], \u002F\u002F Search criteria\n    ['name' => 'John Updated', 'password' => bcrypt('newpass')]\n);\n\n\u002F\u002F Method 7: Insert multiple (mass insert, no events)\nUser::insert([\n    ['name' => 'User 1', 'email' => 'user1@example.com'],\n    ['name' => 'User 2', 'email' => 'user2@example.com'],\n]);\n```\n\n**Read (Retrieve):**\n\n```php\n\u002F\u002F All records\n$users = User::all();\n\n\u002F\u002F With conditions\n$users = User::where('is_active', true)\n             ->where('role', 'admin')\n             ->get();\n\n\u002F\u002F Single record by ID\n$user = User::find(1);\n\n\u002F\u002F Single record by ID or fail\n$user = User::findOrFail(1); \u002F\u002F Throws ModelNotFoundException\n\n\u002F\u002F First record matching conditions\n$user = User::where('email', 'john@example.com')->first();\n$user = User::where('email', 'john@example.com')->firstOrFail();\n\n\u002F\u002F Pluck single column\n$emails = User::where('is_active', true)->pluck('email');\n\n\u002F\u002F Lists of key-value pairs\n$users = User::pluck('name', 'id'); \u002F\u002F [1 => 'John', 2 => 'Jane']\n\n\u002F\u002F Chunk for memory efficiency\nUser::chunk(100, function ($users) {\n    foreach ($users as $user) {\n        \u002F\u002F Process user\n    }\n});\n\n\u002F\u002F Cursor for extremely large datasets\nforeach (User::where('is_active', true)->cursor() as $user) {\n    \u002F\u002F Process user (low memory usage)\n}\n\n\u002F\u002F Aggregates\n$count = User::where('role', 'admin')->count();\n$maxId = User::max('id');\n$minAge = User::min('age');\n$avgAge = User::avg('age');\n$sum = User::sum('points');\n\n\u002F\u002F Exists check\n$exists = User::where('email', 'john@example.com')->exists();\n$doesntExist = User::where('email', 'fake@example.com')->doesntExist();\n\n\u002F\u002F Select specific columns\n$users = User::select('id', 'name', 'email')->get();\n\n\u002F\u002F Distinct\n$roles = User::distinct()->pluck('role');\n\n\u002F\u002F Ordering\n$users = User::orderBy('name', 'asc')\n             ->orderBy('created_at', 'desc')\n             ->get();\n\n\u002F\u002F Latest and oldest\n$latest = User::latest()->first();\n$oldest = User::oldest()->first();\n\n\u002F\u002F Random\n$random = User::inRandomOrder()->first();\n\n\u002F\u002F Pagination\n$users = User::paginate(15); \u002F\u002F 15 per page\n$users = User::simplePaginate(15); \u002F\u002F Previous\u002Fnext only\n$users = User::cursorPaginate(15); \u002F\u002F Cursor pagination for large datasets\n```\n\n**Update:**\n\n```php\n\u002F\u002F Method 1: Find and update\n$user = User::find(1);\n$user->name = 'Updated Name';\n$user->save();\n\n\u002F\u002F Method 2: Mass update\nUser::where('role', 'user')\n    ->update(['is_active' => false]);\n\n\u002F\u002F Method 3: Update with query\nUser::where('id', 1)->update([\n    'name' => 'New Name',\n    'email' => 'new@example.com',\n]);\n\n\u002F\u002F Method 4: Update or create\n$user = User::updateOrCreate(\n    ['email' => 'john@example.com'],\n    ['name' => 'John Updated', 'is_active' => true]\n);\n\n\u002F\u002F Method 5: Increment\u002FDecrement\nUser::where('id', 1)->increment('login_count');\nUser::where('id', 1)->increment('points', 10);\nUser::where('id', 1)->decrement('stock', 2);\n\n\u002F\u002F Method 6: Multiple increments\nUser::where('id', 1)->incrementEach([\n    'login_count' => 1,\n    'points' => 5,\n]);\n```\n\n**Delete:**\n\n```php\n\u002F\u002F Method 1: Find and delete\n$user = User::find(1);\n$user->delete();\n\n\u002F\u002F Method 2: Delete by query\nUser::where('is_active', false)->delete();\n\n\u002F\u002F Method 3: Delete by ID\nUser::destroy(1);\nUser::destroy([1, 2, 3]);\nUser::destroy(1, 2, 3);\n\n\u002F\u002F Method 4: Force delete (if using soft deletes)\n$user->forceDelete();\n\n\u002F\u002F Method 5: Truncate (delete all, reset auto-increment)\nUser::truncate();\n```\n\n**Soft Deletes:**\n\n```php\n\u002F\u002F Add to model\nuse Illuminate\\Database\\Eloquent\\SoftDeletes;\n\nclass User extends Model\n{\n    use SoftDeletes;\n    protected $dates = ['deleted_at'];\n}\n\n\u002F\u002F Delete (sets deleted_at timestamp)\n$user->delete();\n\n\u002F\u002F Include soft deleted\n$users = User::withTrashed()->get();\n\n\u002F\u002F Only soft deleted\n$users = User::onlyTrashed()->get();\n\n\u002F\u002F Restore soft deleted\n$user->restore();\n\n\u002F\u002F Force delete permanently\n$user->forceDelete();\n```\n\n**Scopes:**\n\n```php\n\u002F\u002F Local scope in model\npublic function scopeActive($query)\n{\n    return $query->where('is_active', true);\n}\n\npublic function scopeRole($query, $role)\n{\n    return $query->where('role', $role);\n}\n\n\u002F\u002F Usage\n$users = User::active()->role('admin')->get();\n\n\u002F\u002F Dynamic scopes\npublic function scopeWhereLike($query, $column, $value)\n{\n    return $query->where($column, 'LIKE', '%' . $value . '%');\n}\n\n\u002F\u002F Global scope\nprotected static function booted()\n{\n    static::addGlobalScope('active', function (Builder $builder) {\n        $builder->where('is_active', true);\n    });\n}\n```\n\n**Common Mistakes:**\n- Not using mass assignment protection\n- Forgetting to hash passwords\n- N+1 query problem (use eager loading)\n- Loading all records with `all()` on large tables\n- Not using transactions for multiple operations\n\n**Performance Optimization:**\n\n```php\n\u002F\u002F Use chunking for large datasets\nUser::chunk(500, function ($users) {\n    foreach ($users as $user) {\n        \u002F\u002F Process\n    }\n});\n\n\u002F\u002F Use cursor for memory efficiency\nforeach (User::cursor() as $user) {\n    \u002F\u002F Process\n}\n\n\u002F\u002F Use select for specific columns\nUser::select('id', 'name')->get();\n\n\u002F\u002F Use caching\n$users = Cache::remember('active_users', 3600, function () {\n    return User::active()->get();\n});\n```\n\n**Security:**\n- Always use `$fillable` or `$guarded` for mass assignment\n- Hash passwords before saving\n- Validate input before creating\u002Fupdating\n- Use route model binding with `findOrFail`\n\n**Follow-up Questions:**\n- What's the difference between `save()` and `update()`?\n- How does mass assignment protection work?\n- What are the performance implications of different retrieval methods?\n- How do you handle model events?",[62,63,64],"Eloquent","CRUD","ORM",{"id":66,"category":67,"question":68,"answer":69,"level":10,"tags":70},8,"Validation","How do you perform validation in Laravel using Form Requests and Validators?","Laravel provides multiple ways to validate data with powerful validation rules and error handling.\n\n**Basic Validation in Controller:**\n\n```php\nuse Illuminate\\Support\\Facades\\Validator;\n\npublic function store(Request $request)\n{\n    $validator = Validator::make($request->all(), [\n        'name' => 'required|string|max:255',\n        'email' => 'required|email|unique:users',\n        'password' => 'required|string|min:8|confirmed',\n        'age' => 'nullable|integer|min:18',\n        'website' => 'nullable|url',\n        'birth_date' => 'date|before:today',\n    ]);\n\n    if ($validator->fails()) {\n        return redirect()->back()\n            ->withErrors($validator)\n            ->withInput();\n    }\n\n    \u002F\u002F Validation passed\n}\n\n\u002F\u002F Using validate() method (automatic redirect on failure)\npublic function store(Request $request)\n{\n    $validated = $request->validate([\n        'name' => 'required|string|max:255',\n        'email' => 'required|email|unique:users',\n        'password' => 'required|string|min:8',\n    ]);\n\n    \u002F\u002F $validated contains only validated data\n}\n```\n\n**Form Request Validation:**\n\n```bash\nphp artisan make:request StoreUserRequest\n```\n\n```php\nnamespace App\\Http\\Requests;\n\nuse Illuminate\\Foundation\\Http\\FormRequest;\nuse Illuminate\\Validation\\Rule;\n\nclass StoreUserRequest extends FormRequest\n{\n    \u002F**\n     * Determine if the user is authorized to make this request.\n     *\u002F\n    public function authorize(): bool\n    {\n        \u002F\u002F Add custom authorization logic\n        return $this->user()->isAdmin();\n    }\n\n    \u002F**\n     * Get the validation rules that apply to the request.\n     *\u002F\n    public function rules(): array\n    {\n        return [\n            'name' => ['required', 'string', 'max:255'],\n            'email' => ['required', 'email', Rule::unique('users')->ignore($this->user)],\n            'password' => ['required', 'string', 'min:8', 'confirmed'],\n            'role' => ['required', Rule::in(['admin', 'user', 'moderator'])],\n            'profile.image' => ['nullable', 'image', 'max:2048'],\n            'profile.bio' => ['nullable', 'string', 'max:1000'],\n            'settings.*' => ['nullable', 'string'], \u002F\u002F Array validation\n        ];\n    }\n\n    \u002F**\n     * Custom error messages.\n     *\u002F\n    public function messages(): array\n    {\n        return [\n            'name.required' => 'A name is required.',\n            'email.unique' => 'This email is already taken.',\n            'password.min' => 'Password must be at least 8 characters.',\n        ];\n    }\n\n    \u002F**\n     * Prepare the data for validation.\n     *\u002F\n    protected function prepareForValidation(): void\n    {\n        $this->merge([\n            'email' => strtolower($this->email),\n            'name' => trim($this->name),\n        ]);\n    }\n\n    \u002F**\n     * Configure the validator instance.\n     *\u002F\n    public function withValidator($validator): void\n    {\n        $validator->after(function ($validator) {\n            if ($this->somethingElseIsInvalid()) {\n                $validator->errors()->add('field', 'Something is wrong!');\n            }\n        });\n    }\n\n    \u002F**\n     * Get validated data with custom transformations.\n     *\u002F\n    public function validated(): array\n    {\n        $validated = parent::validated();\n        $validated['password'] = bcrypt($validated['password']);\n        return $validated;\n    }\n}\n\n\u002F\u002F Usage in controller\npublic function store(StoreUserRequest $request)\n{\n    \u002F\u002F Request is already validated and authorized\n    $validated = $request->validated();\n    User::create($validated);\n\n    return redirect()->route('users.index');\n}\n```\n\n**All Validation Rules:**\n\n```php\n\u002F\u002F Basics\n'field' => 'required'              \u002F\u002F Field must be present\n'field' => 'nullable'              \u002F\u002F Field can be null\n'field' => 'string'                \u002F\u002F Must be string\n'field' => 'integer'               \u002F\u002F Must be integer\n'field' => 'numeric'               \u002F\u002F Must be numeric\n'field' => 'boolean'               \u002F\u002F Must be boolean (true\u002Ffalse\u002F1\u002F0\u002F\"1\"\u002F\"0\")\n'field' => 'array'                 \u002F\u002F Must be array\n'field' => 'object'                \u002F\u002F Must be object\n'field' => 'file'                  \u002F\u002F Must be uploaded file\n\n\u002F\u002F Sizes and ranges\n'field' => 'min:10'                \u002F\u002F Minimum value\u002Flength\n'field' => 'max:100'               \u002F\u002F Maximum value\u002Flength\n'field' => 'size:50'               \u002F\u002F Exact size\n'field' => 'between:10,100'        \u002F\u002F Between min and max\n\n\u002F\u002F Strings\n'field' => 'email'                 \u002F\u002F Valid email format\n'field' => 'url'                   \u002F\u002F Valid URL\n'field' => 'ip'                    \u002F\u002F Valid IP address\n'field' => 'ipv4'                  \u002F\u002F Valid IPv4\n'field' => 'ipv6'                  \u002F\u002F Valid IPv6\n'field' => 'uuid'                  \u002F\u002F Valid UUID\n'field' => 'regex:\u002F^[a-z]+$\u002Fi'    \u002F\u002F Regular expression\n'field' => 'alpha'                 \u002F\u002F Only alphabetic characters\n'field' => 'alpha_dash'            \u002F\u002F Letters, numbers, dashes, underscores\n'field' => 'alpha_num'             \u002F\u002F Letters and numbers only\n\n\u002F\u002F Dates\n'field' => 'date'                  \u002F\u002F Valid date\n'field' => 'date_format:Y-m-d'    \u002F\u002F Specific date format\n'field' => 'before:today'          \u002F\u002F Before given date\n'field' => 'after:tomorrow'        \u002F\u002F After given date\n'field' => 'before_or_equal:now'   \u002F\u002F Before or equal\n'field' => 'after_or_equal:yesterday' \u002F\u002F After or equal\n\n\u002F\u002F Uniqueness and existence\n'email' => 'unique:users'          \u002F\u002F Unique in table\n'email' => 'unique:users,email,' . $id  \u002F\u002F Ignore specific ID\n'user_id' => 'exists:users,id'     \u002F\u002F Exists in table\n\n\u002F\u002F Files\n'photo' => 'image'                 \u002F\u002F Must be image\n'photo' => 'mimes:jpeg,png'        \u002F\u002F Allowed MIME types\n'photo' => 'max:2048'              \u002F\u002F Maximum file size in KB\n'photo' => 'dimensions:min_width=100,min_height=200'  \u002F\u002F Image dimensions\n\n\u002F\u002F Conditional\n'field' => 'required_if:other,value'      \u002F\u002F Required if other equals value\n'field' => 'required_unless:other,value'  \u002F\u002F Required unless other equals value\n'field' => 'required_with:foo,bar'        \u002F\u002F Required if any of those fields present\n'field' => 'required_without:foo'         \u002F\u002F Required if any of those fields missing\n'field' => 'prohibited_if:other,value'    \u002F\u002F Prohibited if other equals value\n'field' => 'prohibited_unless:other,value' \u002F\u002F Prohibited unless other equals value\n\n\u002F\u002F Arrays\n'items.*' => 'required'            \u002F\u002F Validate each array item\n'items.*.id' => 'exists:items,id'  \u002F\u002F Nested array validation\n\n\u002F\u002F Passwords\n'password' => 'confirmed'          \u002F\u002F Must match password_confirmation field\n'current_password' => 'current_password'  \u002F\u002F Must match current user password\n\n\u002F\u002F Custom rules\n'field' => new CustomRule()         \u002F\u002F Custom rule object\n```\n\n**Custom Validation Rules:**\n\n```bash\nphp artisan make:rule Uppercase\n```\n\n```php\n\u002F\u002F Rule class\nnamespace App\\Rules;\n\nuse Closure;\nuse Illuminate\\Contracts\\Validation\\ValidationRule;\n\nclass Uppercase implements ValidationRule\n{\n    public function validate(string $attribute, mixed $value, Closure $fail): void\n    {\n        if (strtoupper($value) !== $value) {\n            $fail('The :attribute must be uppercase.');\n        }\n    }\n}\n\n\u002F\u002F Using the rule\nuse App\\Rules\\Uppercase;\n\n'code' => ['required', new Uppercase]\n\n\u002F\u002F Custom rule using Rule facade\nValidator::extend('uppercase', function ($attribute, $value, $parameters, $validator) {\n    return strtoupper($value) === $value;\n});\n\n\u002F\u002F Rule with parameters\nclass MinWords implements ValidationRule\n{\n    public function __construct(protected int $minWords) {}\n\n    public function validate(string $attribute, mixed $value, Closure $fail): void\n    {\n        if (str_word_count($value) \u003C $this->minWords) {\n            $fail(\"The :attribute must have at least {$this->minWords} words.\");\n        }\n    }\n}\n\n'description' => ['required', new MinWords(10)];\n```\n\n**Conditional Validation:**\n\n```php\n\u002F\u002F Sometimes rule\n$validator = Validator::make($data, [\n    'email' => 'sometimes|required|email', \u002F\u002F Validate only if present\n]);\n\n\u002F\u002F Custom conditions\n$validator = Validator::make($data, [\n    'payment_method' => 'required|in:credit_card,paypal',\n]);\n\n$validator->sometimes('credit_card_number', 'required|digits:16', function ($input) {\n    return $input->payment_method === 'credit_card';\n});\n\n$validator->sometimes('paypal_email', 'required|email', function ($input) {\n    return $input->payment_method === 'paypal';\n});\n```\n\n**Error Handling and Display:**\n\n```blade\n{{-- Display all errors --}}\n@if($errors->any())\n    \u003Cdiv class=\"alert alert-danger\">\n        \u003Cul>\n            @foreach($errors->all() as $error)\n                \u003Cli>{{ $error }}\u003C\u002Fli>\n            @endforeach\n        \u003C\u002Ful>\n    \u003C\u002Fdiv>\n@endif\n\n{{-- Display specific field error --}}\n\u003Cinput type=\"text\" name=\"email\" value=\"{{ old('email') }}\">\n@error('email')\n    \u003Cdiv class=\"alert alert-danger\">{{ $message }}\u003C\u002Fdiv>\n@enderror\n\n{{-- Custom error bags --}}\n\u003Cinput type=\"text\" name=\"email\" value=\"{{ old('email') }}\">\n@error('email', 'registration')\n    \u003Cdiv class=\"alert alert-danger\">{{ $message }}\u003C\u002Fdiv>\n@enderror\n\n{{-- Manual error bag --}}\nreturn redirect()->back()->withErrors($validator, 'registration');\n```\n\n**Request Validation Best Practices:**\n\n```php\n\u002F\u002F Use Form Requests for complex validation\n\u002F\u002F Use array syntax for multiple rules\n\u002F\u002F Create custom rule objects for reusable validation\n\u002F\u002F Use sometimes() for conditional fields\n\u002F\u002F Always sanitize input using prepareForValidation\n\n\u002F\u002F Example: Complex validation\nclass UpdateUserSettingsRequest extends FormRequest\n{\n    public function rules(): array\n    {\n        return [\n            'preferences' => ['required', 'array'],\n            'preferences.theme' => ['string', Rule::in(['light', 'dark'])],\n            'preferences.notifications' => ['boolean'],\n            'preferences.language' => ['string', 'size:2'],\n            'metadata' => ['nullable', 'array'],\n            'metadata.*.key' => ['required_with:metadata', 'string'],\n            'metadata.*.value' => ['required_with:metadata', 'string'],\n        ];\n    }\n\n    protected function prepareForValidation(): void\n    {\n        $this->merge([\n            'preferences' => array_merge([\n                'theme' => 'light',\n                'notifications' => true,\n            ], $this->preferences ?? []),\n        ]);\n    }\n}\n```\n\n**Security Considerations:**\n- Always validate on the server side (client validation is just UX)\n- Use `confirmed` rule for password confirmation\n- Validate file uploads with `mimes` and `max` rules\n- Use `exists` and `unique` rules with care (they execute queries)\n- Sanitize input before validation when needed\n\n**Performance Considerations:**\n- Cache validation rules when possible\n- Use sometimes() to skip unnecessary validation\n- Avoid complex custom rules that execute heavy queries\n- Use batch validation for multiple similar fields\n\n**Common Mistakes:**\n- Not validating data before using it\n- Forgetting to use `old()` helper to repopulate forms\n- Not handling validation exceptions in APIs\n- Using `required` without `nullable` for optional fields\n- Not using `confirmed` for password fields\n\n**Follow-up Questions:**\n- How do you validate nested array data?\n- What's the difference between Form Request and manual validation?\n- How do you create custom validation rules?\n- How do you handle validation in API responses?",[67,71,72],"Form Requests","Error Handling",{"id":74,"category":75,"question":76,"answer":77,"level":10,"tags":78},9,"Authentication Basics","How does Laravel's authentication system work?","Laravel provides a complete authentication system including user registration, login, password reset, and email verification.\n\n**Basic Setup:**\n\n```bash\n# Laravel UI (for Laravel 8-10)\ncomposer require laravel\u002Fui\nphp artisan ui bootstrap --auth\nnpm install && npm run dev\n\n# Laravel Breeze (minimal)\ncomposer require laravel\u002Fbreeze\nphp artisan breeze:install\nnpm install && npm run dev\n\n# Laravel Jetstream (more features)\ncomposer require laravel\u002Fjetstream\nphp artisan jetstream:install livewire\nnpm install && npm run dev\n```\n\n**Authentication Configuration:**\n\n```php\n\u002F\u002F config\u002Fauth.php\nreturn [\n    'defaults' => [\n        'guard' => 'web',\n        'passwords' => 'users',\n    ],\n\n    'guards' => [\n        'web' => [\n            'driver' => 'session',\n            'provider' => 'users',\n        ],\n        'api' => [\n            'driver' => 'token',\n            'provider' => 'users',\n        ],\n    ],\n\n    'providers' => [\n        'users' => [\n            'driver' => 'eloquent',\n            'model' => App\\Models\\User::class,\n        ],\n    ],\n\n    'passwords' => [\n        'users' => [\n            'provider' => 'users',\n            'table' => 'password_resets',\n            'expire' => 60,\n            'throttle' => 60,\n        ],\n    ],\n];\n```\n\n**Manual Authentication:**\n\n```php\nuse Illuminate\\Support\\Facades\\Auth;\n\nclass LoginController extends Controller\n{\n    public function login(Request $request)\n    {\n        $credentials = $request->validate([\n            'email' => ['required', 'email'],\n            'password' => ['required'],\n        ]);\n\n        \u002F\u002F Attempt to authenticate\n        if (Auth::attempt($credentials, $request->boolean('remember'))) {\n            $request->session()->regenerate();\n\n            return redirect()->intended('dashboard');\n        }\n\n        return back()->withErrors([\n            'email' => 'The provided credentials do not match our records.',\n        ])->onlyInput('email');\n    }\n\n    public function logout(Request $request)\n    {\n        Auth::logout();\n\n        $request->session()->invalidate();\n        $request->session()->regenerateToken();\n\n        return redirect('\u002F');\n    }\n}\n```\n\n**Protecting Routes:**\n\n```php\n\u002F\u002F Route middleware\nRoute::get('\u002Fdashboard', function () {\n    return view('dashboard');\n})->middleware('auth');\n\n\u002F\u002F Controller middleware\nclass DashboardController extends Controller\n{\n    public function __construct()\n    {\n        $this->middleware('auth');\n    }\n}\n\n\u002F\u002F Group middleware\nRoute::middleware(['auth'])->group(function () {\n    Route::get('\u002Fprofile', [ProfileController::class, 'edit']);\n    Route::put('\u002Fprofile', [ProfileController::class, 'update']);\n});\n```\n\n**Getting Authenticated User:**\n\n```php\n\u002F\u002F Via Auth facade\n$user = Auth::user();\n$id = Auth::id();\n$isLoggedIn = Auth::check();\n\n\u002F\u002F Via helper\n$user = auth()->user();\n$isLoggedIn = auth()->check();\n\n\u002F\u002F Via request\n$user = $request->user();\n\n\u002F\u002F Via blade\n@auth\n    \u003Cp>Welcome, {{ auth()->user()->name }}\u003C\u002Fp>\n@endauth\n\n@guest\n    \u003Cp>Please log in\u003C\u002Fp>\n@endguest\n```\n\n**Password Hashing:**\n\n```php\nuse Illuminate\\Support\\Facades\\Hash;\n\n\u002F\u002F Hashing\n$hashedPassword = Hash::make('plain-text-password');\n\n\u002F\u002F Verification\nif (Hash::check('plain-text', $hashedPassword)) {\n    \u002F\u002F Password matches\n}\n\n\u002F\u002F Check if password needs rehash\nif (Hash::needsRehash($hashedPassword)) {\n    $hashedPassword = Hash::make('plain-text');\n}\n```\n\n**Password Reset:**\n\n```php\nuse Illuminate\\Support\\Facades\\Password;\n\nclass ForgotPasswordController extends Controller\n{\n    public function sendResetLink(Request $request)\n    {\n        $request->validate(['email' => 'required|email']);\n\n        $status = Password::sendResetLink(\n            $request->only('email')\n        );\n\n        return $status === Password::RESET_LINK_SENT\n            ? back()->with(['status' => __($status)])\n            : back()->withErrors(['email' => __($status)]);\n    }\n\n    public function resetPassword(Request $request)\n    {\n        $request->validate([\n            'token' => 'required',\n            'email' => 'required|email',\n            'password' => 'required|min:8|confirmed',\n        ]);\n\n        $status = Password::reset(\n            $request->only('email', 'password', 'password_confirmation', 'token'),\n            function ($user, $password) {\n                $user->password = Hash::make($password);\n                $user->save();\n            }\n        );\n\n        return $status === Password::PASSWORD_RESET\n            ? redirect()->route('login')->with('status', __($status))\n            : back()->withErrors(['email' => [__($status)]]);\n    }\n}\n```\n\n**Email Verification:**\n\n```php\n\u002F\u002F User model must implement MustVerifyEmail\nuse Illuminate\\Contracts\\Auth\\MustVerifyEmail;\n\nclass User extends Authenticatable implements MustVerifyEmail\n{\n    \u002F\u002F ...\n}\n\n\u002F\u002F Routes requiring verification\nRoute::get('\u002Fdashboard', function () {\n    \u002F\u002F\n})->middleware(['auth', 'verified']);\n\n\u002F\u002F Manually resend verification\n$request->user()->sendEmailVerificationNotification();\n```\n\n**Custom Authentication:**\n\n```php\n\u002F\u002F Custom guard driver\nAuth::extend('custom', function ($app, $name, array $config) {\n    return new CustomGuard(\n        Auth::createUserProvider($config['provider']),\n        $app['session.store']\n    );\n});\n\n\u002F\u002F Custom user provider\nclass CustomUserProvider implements UserProvider\n{\n    public function retrieveById($identifier) {}\n    public function retrieveByToken($identifier, $token) {}\n    public function updateRememberToken(Authenticatable $user, $token) {}\n    public function retrieveByCredentials(array $credentials) {}\n    public function validateCredentials(Authenticatable $user, array $credentials) {}\n}\n\n\u002F\u002F Register provider\nAuth::provider('custom', function ($app, array $config) {\n    return new CustomUserProvider();\n});\n```\n\n**Authentication Events:**\n\n```php\n\u002F\u002F Event listeners\nprotected $listen = [\n    Registered::class => [\n        SendEmailVerificationNotification::class,\n    ],\n    Login::class => [\n        LogSuccessfulLogin::class,\n    ],\n    Logout::class => [\n        LogSuccessfulLogout::class,\n    ],\n    Failed::class => [\n        LogFailedLogin::class,\n    ],\n];\n```\n\n**Security Best Practices:**\n- Use HTTPS in production\n- Implement rate limiting on login attempts\n- Use password confirmation for sensitive actions\n- Regenerate session on login\n- Use `password.confirm` middleware for sensitive operations\n- Store passwords with bcrypt or argon2\n\n**Performance Considerations:**\n- Cache user data when appropriate\n- Use session driver that scales (database, redis)\n- Limit authentication attempts\n\n**Common Mistakes:**\n- Not regenerating session ID on login\n- Storing passwords in plain text\n- Not implementing remember token properly\n- Forgetting to validate email uniqueness\n- Not handling failed authentication attempts\n\n**Follow-up Questions:**\n- How do you implement multi-factor authentication?\n- What's the difference between session and token authentication?\n- How do you handle user impersonation?\n- How does Laravel remember token work?",[79,80,81],"Authentication","Security","Sessions",{"id":83,"category":40,"question":84,"answer":85,"level":10,"tags":86},10,"Explain the complete request lifecycle in Laravel.","The Laravel request lifecycle describes how a request enters the application and returns a response.\n\n**Complete Flow:**\n\n1. **Entry Point (`public\u002Findex.php`)**\n   ```php\n   \u002F\u002F Load Composer autoloader\n   require __DIR__.'\u002F..\u002Fvendor\u002Fautoload.php';\n\n   \u002F\u002F Create application instance\n   $app = require_once __DIR__.'\u002F..\u002Fbootstrap\u002Fapp.php';\n\n   \u002F\u002F Handle request\n   $kernel = $app->make(Kernel::class);\n   $response = $kernel->handle(\n       $request = Request::capture()\n   );\n   $response->send();\n   $kernel->terminate($request, $response);\n   ```\n\n2. **Service Container and Service Providers**\n   ```php\n   \u002F\u002F bootstrap\u002Fapp.php\n   return Application::configure(basePath: dirname(__DIR__))\n       ->withRouting(...)\n       ->withMiddleware(...)\n       ->withExceptions(...)\n       ->create();\n   ```\n\n3. **HTTP Kernel**\n   ```php\n   \u002F\u002F Handles request through middleware pipeline\n   protected $middleware = [\n       \\App\\Http\\Middleware\\TrustProxies::class,\n       \\App\\Http\\Middleware\\HandleCors::class,\n   ];\n   ```\n\n4. **Middleware Pipeline**\n   ```php\n   \u002F\u002F Global middleware (all requests)\n   $request->through([\n       TrustProxies::class,\n       HandleCors::class,\n   ]);\n\n   \u002F\u002F Then route middleware based on route\n   ```\n\n5. **Router**\n   ```php\n   \u002F\u002F Matches request to route\n   $route = $router->dispatch($request);\n   \n   \u002F\u002F Binds route parameters\n   \u002F\u002F Resolves controller\n   ```\n\n6. **Route Middleware**\n   ```php\n   \u002F\u002F Route specific middleware\n   Route::get('\u002Fadmin', function () {\n       \u002F\u002F\n   })->middleware(['auth', 'admin']);\n   ```\n\n7. **Controller**\n   ```php\n   \u002F\u002F Resolved via service container\n   \u002F\u002F Dependencies injected\n   \u002F\u002F Method called with request\n   ```\n\n8. **Response**\n   ```php\n   \u002F\u002F Controller returns response\n   \u002F\u002F Response passes back through middleware\n   \u002F\u002F Response sent to browser\n   ```\n\n**Detailed Steps with Code:**\n\n```php\n\u002F\u002F 1. Bootstrap\n\u002F\u002F Creates application instance\n$app = new Illuminate\\Foundation\\Application(\n    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)\n);\n\n\u002F\u002F Register base service providers\n$app->register(new EventServiceProvider($app));\n$app->register(new RoutingServiceProvider($app));\n\n\u002F\u002F 2. Configure HTTP Kernel\nclass Kernel extends HttpKernel\n{\n    protected $bootstrappers = [\n        \\Illuminate\\Foundation\\Bootstrap\\LoadEnvironmentVariables::class,\n        \\Illuminate\\Foundation\\Bootstrap\\LoadConfiguration::class,\n        \\Illuminate\\Foundation\\Bootstrap\\HandleExceptions::class,\n        \\Illuminate\\Foundation\\Bootstrap\\RegisterFacades::class,\n        \\Illuminate\\Foundation\\Bootstrap\\RegisterProviders::class,\n        \\Illuminate\\Foundation\\Bootstrap\\BootProviders::class,\n    ];\n}\n\n\u002F\u002F 3. Service Providers Registration\n\u002F\u002F Register method of all providers called\nforeach ($this->providers as $provider) {\n    $this->app->register($provider);\n}\n\n\u002F\u002F 4. Service Providers Boot\n\u002F\u002F Boot method of all providers called\nforeach ($this->providers as $provider) {\n    $this->callBootMethod($provider);\n}\n\n\u002F\u002F 5. Route Discovery\n\u002F\u002F Routes from routes\u002Fweb.php and routes\u002Fapi.php\n\u002F\u002F Routes are compiled and stored\n\n\u002F\u002F 6. Request Handling\n\u002F\u002F Kernel receives request\n$response = $kernel->handle($request);\n\n\u002F\u002F 7. Through Middleware Pipeline\n$pipeline = (new Pipeline($this->app))\n    ->send($request)\n    ->through($this->middleware)\n    ->then(function ($request) use ($router) {\n        return $router->dispatch($request);\n    });\n\n\u002F\u002F 8. Router Dispatches\n$route = $this->routes->match($request);\n$request->setRouteResolver(fn() => $route);\n\n\u002F\u002F 9. Route Middleware Stack\n$middleware = $route->gatherMiddleware();\n\n\u002F\u002F 10. Controller Resolution\n$controller = $this->container->make($route->getController());\n\n\u002F\u002F 11. Method Call with Dependency Injection\n$parameters = $this->resolveClassMethodDependencies(\n    $route->parameters(), $controller, $route->getActionMethod()\n);\n\n$response = $controller->{$route->getActionMethod()}(...$parameters);\n\n\u002F\u002F 12. Response Transformation\nif ($response instanceof Responsable) {\n    $response = $response->toResponse($request);\n}\n\n\u002F\u002F 13. Response Sent\n$response->send();\n\n\u002F\u002F 14. Terminate\n$kernel->terminate($request, $response);\n```\n\n**Customizing Lifecycle:**\n\n```php\n\u002F\u002F bootstrap\u002Fapp.php\nreturn Application::configure(basePath: dirname(__DIR__))\n    ->withRouting(\n        web: __DIR__.'\u002F..\u002Froutes\u002Fweb.php',\n        api: __DIR__.'\u002F..\u002Froutes\u002Fapi.php',\n        commands: __DIR__.'\u002F..\u002Froutes\u002Fconsole.php',\n        health: '\u002Fup',\n    )\n    ->withMiddleware(function (Middleware $middleware) {\n        $middleware->web(append: [\n            CustomWebMiddleware::class,\n        ]);\n    })\n    ->withExceptions(function (Exceptions $exceptions) {\n        $exceptions->render(function (InvalidOrderException $e, Request $request) {\n            return response()->view('errors.invalid-order', [], 500);\n        });\n    })\n    ->withSchedule(function (Schedule $schedule) {\n        $schedule->command('emails:send')->daily();\n    })\n    ->withProviders([\n        CustomServiceProvider::class,\n    ])\n    ->create();\n```\n\n**Performance Optimization:**\n- Cache configuration: `php artisan config:cache`\n- Cache routes: `php artisan route:cache`\n- Cache events: `php artisan event:cache`\n- Optimize autoloader: `composer dump-autoload -o`\n\n**Debugging Lifecycle:**\n\n```php\n\u002F\u002F Listen to events\nEvent::listen('Illuminate\\Routing\\Events\\RouteMatched', function ($event) {\n    logger('Route matched: ' . $event->route->getName());\n});\n\n\u002F\u002F Middleware debug\nclass DebugMiddleware\n{\n    public function handle($request, $next)\n    {\n        $start = microtime(true);\n        $response = $next($request);\n        $duration = microtime(true) - $start;\n\n        logger(sprintf('Request took %.2f ms', $duration * 1000));\n\n        return $response;\n    }\n}\n```\n\n**Common Issues:**\n- Service providers registered in wrong order\n- Middleware dependencies not resolved\n- Route caching issues after changes\n- Configuration caching in development\n\n**Security Considerations:**\n- Environment variables loaded before config\n- Exception handling shouldn't expose sensitive data\n- Trust proxies configured correctly\n- CORS middleware order matters\n\n**Follow-up Questions:**\n- What happens if a middleware throws an exception?\n- How does Laravel handle multiple requests concurrently?\n- What's the difference between `register()` and `boot()` in service providers?\n- How can you add custom lifecycle hooks?",[40,20,87],"Kernel",{"id":89,"category":54,"question":90,"answer":91,"level":10,"tags":92},11,"How do you seed and use database factories in Laravel?","Database seeding and factories allow you to populate your database with test data efficiently.\n\n**Creating Factories:**\n\n```bash\nphp artisan make:factory UserFactory\nphp artisan make:factory PostFactory --model=Post\n```\n\n**Factory Definition:**\n\n```php\nnamespace Database\\Factories;\n\nuse App\\Models\\User;\nuse App\\Models\\Post;\nuse Illuminate\\Database\\Eloquent\\Factories\\Factory;\nuse Illuminate\\Support\\Facades\\Hash;\nuse Illuminate\\Support\\Str;\n\nclass UserFactory extends Factory\n{\n    protected $model = User::class;\n\n    public function definition(): array\n    {\n        return [\n            'name' => fake()->name(),\n            'email' => fake()->unique()->safeEmail(),\n            'email_verified_at' => now(),\n            'password' => Hash::make('password'), \u002F\u002F Default password\n            'remember_token' => Str::random(10),\n            'is_active' => fake()->boolean(90), \u002F\u002F 90% active\n            'role' => fake()->randomElement(['user', 'moderator', 'admin']),\n            'age' => fake()->numberBetween(18, 80),\n            'bio' => fake()->paragraph(),\n            'avatar' => fake()->imageUrl(100, 100),\n            'created_at' => fake()->dateTimeBetween('-1 year', 'now'),\n        ];\n    }\n\n    \u002F\u002F States - modify default state\n    public function admin(): static\n    {\n        return $this->state(fn (array $attributes) => [\n            'role' => 'admin',\n            'is_active' => true,\n        ]);\n    }\n\n    public function inactive(): static\n    {\n        return $this->state(fn (array $attributes) => [\n            'is_active' => false,\n            'email_verified_at' => null,\n        ]);\n    }\n\n    public function unverified(): static\n    {\n        return $this->state(fn (array $attributes) => [\n            'email_verified_at' => null,\n        ]);\n    }\n\n    \u002F\u002F Configure method for callbacks\n    public function configure(): static\n    {\n        return $this->afterMaking(function (User $user) {\n            \u002F\u002F After making instance (not saved yet)\n        })->afterCreating(function (User $user) {\n            \u002F\u002F After saved to database\n            $user->assignRole('user'); \u002F\u002F Example: assign role\n        });\n    }\n}\n```\n\n**Relationships in Factories:**\n\n```php\nclass PostFactory extends Factory\n{\n    protected $model = Post::class;\n\n    public function definition(): array\n    {\n        return [\n            'user_id' => User::factory(), \u002F\u002F Create associated user\n            'title' => fake()->sentence(),\n            'content' => fake()->paragraphs(3, true),\n            'published_at' => fake()->optional()->dateTime(),\n            'views' => fake()->numberBetween(0, 10000),\n            'is_featured' => fake()->boolean(20),\n        ];\n    }\n\n    \u002F\u002F Published state\n    public function published(): static\n    {\n        return $this->state(fn (array $attributes) => [\n            'published_at' => fake()->dateTimeBetween('-1 month', 'now'),\n        ]);\n    }\n\n    \u002F\u002F With specific user\n    public function forUser(User $user): static\n    {\n        return $this->state(fn (array $attributes) => [\n            'user_id' => $user->id,\n        ]);\n    }\n\n    \u002F\u002F With comments relationship\n    public function withComments(int $count = 3): static\n    {\n        return $this->has(CommentFactory::factory()->count($count), 'comments');\n    }\n}\n\n\u002F\u002F Usage with relationships\nUser::factory()\n    ->has(Post::factory()->count(5)) \u002F\u002F Create 5 posts\n    ->hasComments(10) \u002F\u002F With custom relationship method\n    ->create();\n```\n\n**Using Factories:**\n\n```php\n\u002F\u002F Create single record\n$user = User::factory()->create();\n\n\u002F\u002F Create with specific attributes\n$admin = User::factory()->admin()->create([\n    'email' => 'admin@example.com',\n]);\n\n\u002F\u002F Create multiple\n$users = User::factory()->count(10)->create();\n\n\u002F\u002F Make (not persisted)\n$user = User::factory()->make();\n\n\u002F\u002F Make multiple\n$users = User::factory()->count(5)->make();\n\n\u002F\u002F Create with relationships\n$user = User::factory()\n    ->has(Post::factory()->count(3))\n    ->create();\n\n$user = User::factory()\n    ->hasPosts(5) \u002F\u002F Magic method\n    ->create();\n\n\u002F\u002F Create for specific relationship\n$post = Post::factory()\n    ->for(User::factory()->admin(), 'user')\n    ->create();\n```\n\n**Seeders:**\n\n```bash\nphp artisan make:seeder UserSeeder\nphp artisan make:seeder DatabaseSeeder\n```\n\n```php\nnamespace Database\\Seeders;\n\nuse App\\Models\\User;\nuse App\\Models\\Post;\nuse App\\Models\\Comment;\nuse Illuminate\\Database\\Seeder;\nuse Illuminate\\Support\\Facades\\DB;\nuse Illuminate\\Support\\Facades\\Hash;\n\nclass UserSeeder extends Seeder\n{\n    public function run(): void\n    {\n        \u002F\u002F Create specific users\n        User::create([\n            'name' => 'Admin User',\n            'email' => 'admin@example.com',\n            'password' => Hash::make('password'),\n            'role' => 'admin',\n        ]);\n\n        User::create([\n            'name' => 'Test User',\n            'email' => 'test@example.com',\n            'password' => Hash::make('password'),\n        ]);\n\n        \u002F\u002F Create random users with factory\n        User::factory()->count(50)->create();\n    }\n}\n\n\u002F\u002F DatabaseSeeder\nclass DatabaseSeeder extends Seeder\n{\n    public function run(): void\n    {\n        $this->call([\n            UserSeeder::class,\n            PostSeeder::class,\n            CommentSeeder::class,\n        ]);\n\n        \u002F\u002F Create complex data structure\n        User::factory()\n            ->count(10)\n            ->has(\n                Post::factory()\n                    ->count(5)\n                    ->has(Comment::factory()->count(10))\n            )\n            ->create();\n\n        \u002F\u002F Using callbacks\n        User::factory()\n            ->count(5)\n            ->create()\n            ->each(function ($user) {\n                $user->assignRole('user');\n                $user->profile()->create([\n                    'bio' => fake()->paragraph(),\n                ]);\n            });\n    }\n}\n```\n\n**Advanced Factory Techniques:**\n\n```php\n\u002F\u002F Sequence\nUser::factory()\n    ->count(10)\n    ->sequence(\n        ['role' => 'admin'],\n        ['role' => 'moderator'],\n        ['role' => 'user'],\n    )\n    ->create();\n\n\u002F\u002F Callback sequence\nUser::factory()\n    ->count(10)\n    ->sequence(fn ($sequence) => [\n        'email' => 'user' . $sequence->index . '@example.com',\n    ])\n    ->create();\n\n\u002F\u002F Lazy evaluation\nclass UserFactory extends Factory\n{\n    public function definition(): array\n    {\n        return [\n            'email' => $this->faker->unique()->safeEmail(),\n            'name' => $this->faker->name(),\n            'settings' => function (array $attributes) {\n                \u002F\u002F Access other attributes\n                return ['timezone' => $attributes['timezone'] ?? 'UTC'];\n            },\n        ];\n    }\n}\n\n\u002F\u002F Reusing factories\n$user = User::factory()->create();\nPost::factory()->count(3)->create(['user_id' => $user->id]);\n\n\u002F\u002F Creating from existing data\n$existingUser = User::first();\n$similarUser = User::factory()->make([\n    'email' => 'clone@example.com',\n    'name' => $existingUser->name . ' Clone',\n]);\n```\n\n**Running Seeders:**\n\n```bash\n# Run all seeders\nphp artisan db:seed\n\n# Run specific seeder\nphp artisan db:seed --class=UserSeeder\n\n# Run migrations and seed\nphp artisan migrate --seed\n\n# Refresh and seed\nphp artisan migrate:refresh --seed\n\n# Fresh and seed\nphp artisan migrate:fresh --seed\n\n# Seed in production (careful!)\nphp artisan db:seed --force\n```\n\n**Testing with Factories:**\n\n```php\n\u002F\u002F Tests\u002FFeature\u002FUserTest.php\npublic function test_user_creation()\n{\n    $user = User::factory()->create();\n    \n    $response = $this->actingAs($user)\n        ->get('\u002Fprofile');\n    \n    $response->assertStatus(200);\n}\n\n\u002F\u002F Create with specific data for test scenario\npublic function test_admin_can_view_admin_panel()\n{\n    $admin = User::factory()->admin()->create();\n    \n    $response = $this->actingAs($admin)\n        ->get('\u002Fadmin');\n    \n    $response->assertStatus(200);\n}\n\n\u002F\u002F Using states\npublic function test_inactive_users_cannot_login()\n{\n    $user = User::factory()->inactive()->create();\n    \n    $response = $this->post('\u002Flogin', [\n        'email' => $user->email,\n        'password' => 'password',\n    ]);\n    \n    $response->assertSessionHasErrors('email');\n}\n```\n\n**Performance Optimization:**\n\n```php\n\u002F\u002F Disable model events when seeding\nUser::factory()->count(1000)->create([\n    'email_verified_at' => now(),\n]);\n\n\u002F\u002F Use insert for mass creation\n$users = User::factory()->count(1000)->make()->toArray();\nDB::table('users')->insert($users);\n\n\u002F\u002F Chunking for large datasets\nUser::factory()->count(10000)->create()->each(function ($user) {\n    \u002F\u002F Process in smaller batches\n});\n```\n\n**Best Practices:**\n- Use factories for all test data\n- Keep seeders idempotent (can run multiple times)\n- Use states for common variations\n- Avoid heavy operations in seeders\n- Use sequences for predictable data\n- Separate development and production seeders\n\n**Common Mistakes:**\n- Creating duplicate unique records\n- Not handling foreign key constraints\n- Forgetting to call parent::run() in seeders\n- Using factories in production\n- Not resetting sequences between tests\n\n**Security Considerations:**\n- Don't use real user data in factories\n- Don't seed production with sensitive data\n- Use environment checks for destructive seeding\n\n**Follow-up Questions:**\n- How do you handle complex relationships in factories?\n- What's the difference between `make()` and `create()`?\n- How do you seed polymorphic relationships?\n- Can you use factories for API testing?",[93,94,95],"Seeders","Factories","Testing Data",{"id":97,"category":98,"question":99,"answer":100,"level":10,"tags":101},26,"Beginner","What are named routes and how do you generate URLs for them?","Named routes allow you to generate URLs or redirects to specific routes without hardcoding the URL path.\n\n**Defining Named Routes:**\n\n```php\n\u002F\u002F Basic named route\nRoute::get('\u002Fuser\u002Fprofile', [UserController::class, 'show'])->name('profile');\n\n\u002F\u002F With parameters\nRoute::get('\u002Fuser\u002F{id}\u002Fprofile', [UserController::class, 'show'])->name('profile.show');\n\n\u002F\u002F In a group\nRoute::name('admin.')->prefix('admin')->group(function () {\n    Route::get('\u002Fusers', [UserController::class, 'index'])->name('users');\n    Route::get('\u002Fusers\u002F{id}', [UserController::class, 'show'])->name('users.show');\n});\n\n\u002F\u002F Resource controllers with names\nRoute::resource('posts', PostController::class)->names([\n    'index' => 'posts.all',\n    'show' => 'posts.view',\n]);\n```\n\n**Generating URLs:**\n\n```php\n\u002F\u002F Generate URL for named route\n$url = route('profile');\n\n\u002F\u002F With parameters\n$url = route('profile.show', ['id' => 1]);\n\n\u002F\u002F With query parameters\n$url = route('profile.show', ['id' => 1, 'tab' => 'posts']);\n\n\u002F\u002F Using named route in redirect\nreturn redirect()->route('profile');\n\n\u002F\u002F Using named route in controller\npublic function show($id)\n{\n    return redirect()->route('profile.show', ['id' => $id]);\n}\n```\n\n**Signed URLs (Laravel 9+):**\n\n```php\n\u002F\u002F Generate signed URL\n$url = URL::signedRoute('unsubscribe', ['user' => 1]);\n\n\u002F\u002F Temporary signed URL (expires in 30 minutes)\n$url = URL::temporarySignedRoute(\n    'unsubscribe', now()->addMinutes(30), ['user' => 1]\n);\n\n\u002F\u002F Verifying signed URL in route\nRoute::get('\u002Funsubscribe\u002F{user}', function ($user) {\n    \u002F\u002F URL is automatically verified\n})->name('unsubscribe')->middleware('signed');\n```\n\n**Common Mistakes:**\n- Changing route URI but forgetting to update named route references\n- Not passing required parameters to `route()` helper\n- Using `signed` middleware without generating signed URLs\n\n**Follow-up Questions:**\n- What's the difference between `route()` and `url()` helpers?\n- How do you get the current route name?\n- Can you group routes with namespaces and prefixes together?",[7,102,103],"Named Routes","URL Generation",{"id":105,"category":98,"question":106,"answer":107,"level":10,"tags":108},27,"What is the difference between `redirect()->route()` and `redirect()->to()`?","`redirect()->route()` uses named routes while `redirect()->to()` uses raw URLs.\n\n**Comparison:**\n\n```php\n\u002F\u002F Using named route (recommended)\nreturn redirect()->route('profile.show', ['id' => 1]);\n\u002F\u002F Generates: \u002Fuser\u002F1\u002Fprofile\n\n\u002F\u002F Using raw URL (not recommended)\nreturn redirect()->to('\u002Fuser\u002F1\u002Fprofile');\n\n\u002F\u002F Using back\nreturn redirect()->back();\n\n\u002F\u002F Using intended (after login)\nreturn redirect()->intended('\u002Fdashboard');\n\n\u002F\u002F Using action\nreturn redirect()->action([UserController::class, 'show'], ['id' => 1]);\n```\n\n**Why Named Routes Are Better:**\n- If URL changes, only route definition needs updating\n- Easier to maintain in large applications\n- IDE autocomplete support\n- Parameters are automatically handled\n\n**Follow-up Questions:**\n- How does `redirect()->intended()` work?\n- What's the difference between `back()` and `previous()`?",[7,109],"Redirects",{"id":111,"category":98,"question":112,"answer":113,"level":10,"tags":114},28,"How do you handle file uploads in Laravel?","Laravel provides a clean API for handling file uploads with validation and storage.\n\n**Basic File Upload:**\n\n```php\npublic function upload(Request $request)\n{\n    $request->validate([\n        'avatar' => 'required|image|mimes:jpeg,png,jpg|max:2048',\n    ]);\n\n    if ($request->hasFile('avatar')) {\n        $file = $request->file('avatar');\n        \n        \u002F\u002F Get original name\n        $originalName = $file->getClientOriginalName();\n        \n        \u002F\u002F Get extension\n        $extension = $file->getClientOriginalExtension();\n        \n        \u002F\u002F Get size in bytes\n        $size = $file->getSize();\n        \n        \u002F\u002F Store file\n        $path = $file->store('avatars', 'public');\n        \n        \u002F\u002F Store with custom name\n        $path = $file->storeAs('avatars', 'user_' . auth()->id() . '.' . $extension, 'public');\n        \n        \u002F\u002F Save path to database\n        auth()->user()->update(['avatar' => $path]);\n    }\n}\n```\n\n**Validation Rules for Files:**\n\n```php\n'photo' => 'required|file|image|mimes:jpeg,png|max:2048|dimensions:min_width=100,min_height=100'\n'document' => 'required|file|mimes:pdf,doc,docx|max:10240'\n'video' => 'required|file|mimetypes:video\u002Fmp4,video\u002Fquicktime|max:51200'\n```\n\n**Custom File Names:**\n\n```php\n$file = $request->file('avatar');\n$fileName = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();\n$path = $file->storeAs('avatars', $fileName, 'public');\n```\n\n**Multiple Files:**\n\n```php\npublic function uploadMultiple(Request $request)\n{\n    $request->validate([\n        'photos.*' => 'required|image|max:2048',\n        'photos' => 'max:5'\n    ]);\n\n    $paths = [];\n    foreach ($request->file('photos') as $photo) {\n        $paths[] = $photo->store('gallery', 'public');\n    }\n    \n    return response()->json(['paths' => $paths]);\n}\n```\n\n**Security Considerations:**\n- Always validate file types (don't trust client extensions)\n- Use `mimes` or `mimetypes` validation\n- Limit file size\n- Store files outside public directory for sensitive files\n- Scan uploaded files for malware in production\n\n**Follow-up Questions:**\n- How do you stream large file uploads?\n- What's the difference between `store()` and `storeAs()`?\n- How do you handle chunked file uploads?",[115,116,67],"File Uploads","Storage",{"id":118,"category":98,"question":119,"answer":120,"level":10,"tags":121},29,"What is the purpose of `php artisan tinker`?","Tinker is a REPL (Read-Eval-Print Loop) that allows you to interact with your Laravel application from the command line.\n\n**Common Uses:**\n\n```bash\n# Start tinker\nphp artisan tinker\n\n# Run single command\nphp artisan tinker --execute=\"echo app()->version()\"\n```\n\n**Inside Tinker:**\n\n```php\n\u002F\u002F Query database\n>>> App\\Models\\User::all();\n>>> App\\Models\\User::find(1);\n>>> App\\Models\\User::where('email', 'like', '%@gmail.com')->get();\n\n\u002F\u002F Create records\n>>> $user = new App\\Models\\User(['name' => 'John', 'email' => 'john@test.com']);\n>>> $user->save();\n\n\u002F\u002F Call methods\n>>> auth()->user();\n>>> cache()->put('key', 'value', 3600);\n>>> cache()->get('key');\n\n\u002F\u002F Test code snippets\n>>> $result = collect([1, 2, 3])->map(fn($n) => $n * 2);\n>>> $result->toArray();\n\n\u002F\u002F Inspect classes\n>>> dd(config('app'));\n>>> dump(route('home'));\n\n\u002F\u002F Generate data\n>>> App\\Models\\User::factory()->count(10)->create();\n```\n\n**Best Practices:**\n- Use for testing and debugging, not for production\n- Be careful with destructive operations\n- Use `$user->delete()` with caution\n- Great for testing Eloquent queries\n\n**Follow-up Questions:**\n- Can tinker execute Artisan commands?\n- How do you load custom classes in tinker?",[26,122,123,124],"Tinker","REPL","Debugging",{"id":126,"category":98,"question":127,"answer":128,"level":10,"tags":129},30,"What are accessors and mutators in Eloquent?","Accessors and mutators allow you to format Eloquent attribute values when retrieving or setting them on model instances.\n\n**Accessors (Getting Values):**\n\n```php\nclass User extends Model\n{\n    \u002F\u002F Basic accessor\n    public function getFullNameAttribute(): string\n    {\n        return \"{$this->first_name} {$this->last_name}\";\n    }\n\n    \u002F\u002F With transformation\n    public function getEmailAttribute($value): string\n    {\n        return strtolower($value);\n    }\n\n    \u002F\u002F Date formatting\n    public function getCreatedAtAttribute($value): string\n    {\n        return Carbon::parse($value)->format('M d, Y');\n    }\n\n    \u002F\u002F JSON casting\n    public function getSettingsAttribute($value): array\n    {\n        return json_decode($value, true) ?? [];\n    }\n}\n\n\u002F\u002F Usage\n$user = User::find(1);\necho $user->full_name; \u002F\u002F \"John Doe\"\necho $user->email; \u002F\u002F \"john@example.com\"\necho $user->created_at; \u002F\u002F \"Jan 15, 2024\"\n```\n\n**Mutators (Setting Values):**\n\n```php\nclass User extends Model\n{\n    \u002F\u002F Basic mutator\n    public function setFirstNameAttribute($value): void\n    {\n        $this->attributes['first_name'] = ucfirst(strtolower($value));\n    }\n\n    \u002F\u002F Hash password automatically\n    public function setPasswordAttribute($value): void\n    {\n        $this->attributes['password'] = bcrypt($value);\n    }\n\n    \u002F\u002F JSON encoding\n    public function setSettingsAttribute($value): void\n    {\n        $this->attributes['settings'] = json_encode($value);\n    }\n\n    \u002F\u002F Date mutator\n    public function setBirthDateAttribute($value): void\n    {\n        $this->attributes['birth_date'] = Carbon::parse($value);\n    }\n}\n\n\u002F\u002F Usage\n$user = new User();\n$user->first_name = 'john'; \u002F\u002F Stored as \"John\"\n$user->password = 'secret'; \u002F\u002F Automatically hashed\n$user->settings = ['theme' => 'dark']; \u002F\u002F JSON encoded\n```\n\n**Date Casts (Alternative to Accessors):**\n\n```php\nclass User extends Model\n{\n    protected $casts = [\n        'email_verified_at' => 'datetime',\n        'settings' => 'array',\n        'is_admin' => 'boolean',\n        'metadata' => 'json',\n        'created_at' => 'datetime:Y-m-d', \u002F\u002F Custom format\n    ];\n}\n```\n\n**Common Mistakes:**\n- Forgetting to use `$this->attributes` in mutators (causes infinite loops)\n- Not handling null values\n- Overusing accessors for complex transformations (use resources instead)\n\n**Performance Tip:** Accessors don't affect database queries; they run on retrieved models only.\n\n**Follow-up Questions:**\n- What's the difference between accessors and casts?\n- Can you create accessors for non-existent attributes?\n- How do you add accessors to API responses automatically?",[62,130,131,132],"Accessors","Mutators","Casts",{"id":134,"category":98,"question":135,"answer":136,"level":10,"tags":137},31,"What is route model binding and how does it work?","Route model binding automatically injects model instances directly into your routes, eliminating manual `find()` calls.\n\n**Implicit Binding:**\n\n```php\n\u002F\u002F routes\u002Fweb.php\nRoute::get('\u002Fusers\u002F{user}', function (User $user) {\n    return view('users.show', ['user' => $user]);\n});\n\n\u002F\u002F Laravel automatically: User::findOrFail($user)\n\u002F\u002F Returns 404 if not found\n```\n\n**Customizing the Key:**\n\n```php\n\u002F\u002F In User model\npublic function getRouteKeyName()\n{\n    return 'slug'; \u002F\u002F Use 'slug' column instead of 'id'\n}\n\n\u002F\u002F Route now uses slug\nRoute::get('\u002Fusers\u002F{user}', function (User $user) {\n    return $user; \u002F\u002F Finds by slug column\n});\n```\n\n**Explicit Binding:**\n\n```php\n\u002F\u002F AppServiceProvider\nuse App\\Models\\User;\nuse Illuminate\\Support\\Facades\\Route;\n\npublic function boot()\n{\n    Route::bind('user', function ($value) {\n        return User::where('active', true)->findOrFail($value);\n    });\n    \n    \u002F\u002F With custom logic\n    Route::bind('post', function ($value) {\n        return Post::with('comments')->findOrFail($value);\n    });\n}\n```\n\n**Child Route Binding:**\n\n```php\n\u002F\u002F Automatically scope child to parent\nRoute::get('\u002Fusers\u002F{user}\u002Fposts\u002F{post:slug}', function (User $user, Post $post) {\n    \u002F\u002F $post is automatically scoped to $user\n    return $post;\n});\n\n\u002F\u002F Custom child binding\nRoute::get('\u002Fusers\u002F{user}\u002Fposts\u002F{post}', function (User $user, Post $post) {\n    \u002F\u002F Explicitly ensure post belongs to user\n})->scopeBindings();\n```\n\n**Soft Deletes with Model Binding:**\n\n```php\n\u002F\u002F Include soft deleted models\nRoute::get('\u002Fusers\u002F{user}', function (User $user) {\n    return $user;\n})->withTrashed();\n```\n\n**Benefits:**\n- Cleaner controller code\n- Automatic 404 handling\n- Type hinting for better IDE support\n\n**Common Mistakes:**\n- Forgetting to type-hint the model in controller\n- Not matching parameter name with variable name\n- Binding the wrong model for the parameter\n\n**Follow-up Questions:**\n- How do you customize the 404 response for model binding?\n- Can you bind multiple models in one route?\n- How does implicit binding work with UUIDs?",[7,138,62],"Model Binding",{"id":140,"category":98,"question":141,"answer":142,"level":10,"tags":143},32,"What are Blade components and when should you use them?","Blade components are reusable pieces of UI with their own logic and templates, better than `@include` for complex UI elements.\n\n**Class-Based Components:**\n\n```bash\nphp artisan make:component Alert\n```\n\n```php\n\u002F\u002F app\u002FView\u002FComponents\u002FAlert.php\nclass Alert extends Component\n{\n    public $type;\n    public $message;\n    \n    public function __construct($type = 'info', $message = null)\n    {\n        $this->type = $type;\n        $this->message = $message;\n    }\n    \n    public function render()\n    {\n        return view('components.alert');\n    }\n}\n```\n\n```blade\n{{-- resources\u002Fviews\u002Fcomponents\u002Falert.blade.php --}}\n\u003Cdiv class=\"alert alert-{{ $type }}\">\n    @if($slot->isEmpty())\n        {{ $message }}\n    @else\n        {{ $slot }}\n    @endif\n\u003C\u002Fdiv>\n```\n\n**Anonymous Components:**\n\n```blade\n{{-- resources\u002Fviews\u002Fcomponents\u002Fbutton.blade.php --}}\n\u003Cbutton {{ $attributes->merge(['class' => 'btn btn-primary']) }}>\n    {{ $slot }}\n\u003C\u002Fbutton>\n```\n\n**Using Components:**\n\n```blade\n{{-- Class component --}}\n\u003Cx-alert type=\"success\" message=\"Operation successful!\" \u002F>\n\n{{-- With slot --}}\n\u003Cx-alert type=\"warning\">\n    \u003Cstrong>Warning!\u003C\u002Fstrong> Your session will expire soon.\n\u003C\u002Fx-alert>\n\n{{-- Anonymous component --}}\n\u003Cx-button class=\"large\">Click Me\u003C\u002Fx-button>\n\n{{-- Component with attributes --}}\n\u003Cx-input name=\"email\" :value=\"old('email')\" required \u002F>\n```\n\n**Component Attributes:**\n\n```blade\n{{-- components\u002Fcard.blade.php --}}\n\u003Cdiv {{ $attributes->class(['card', 'shadow' => $shadow ?? false])->merge(['data-id' => $id ?? '']) }}>\n    \u003Cdiv class=\"card-header\">{{ $header }}\u003C\u002Fdiv>\n    \u003Cdiv class=\"card-body\">{{ $slot }}\u003C\u002Fdiv>\n\u003C\u002Fdiv>\n```\n\n**When to Use Components vs Includes:**\n\n| Use Components | Use @include |\n|----------------|--------------|\n| Complex logic needed | Simple HTML partial |\n| Reusable across app | Single-use snippets |\n| Props and slots | Just data passing |\n| Lifecycle hooks | No lifecycle |\n\n**Follow-up Questions:**\n- What's the difference between anonymous and class-based components?\n- How do you pass data from parent to component?\n- Can components have private methods?",[43,144,145],"Components","UI",{"id":147,"category":98,"question":148,"answer":149,"level":10,"tags":150},33,"How do you create and use custom validation rules?","Custom validation rules allow you to encapsulate complex validation logic into reusable classes.\n\n**Creating Rule Objects:**\n\n```bash\nphp artisan make:rule Uppercase\nphp artisan make:rule ValidTimezone\n```\n\n```php\n\u002F\u002F Using Rule class (Laravel 10+)\nclass Uppercase implements ValidationRule\n{\n    public function validate(string $attribute, mixed $value, Closure $fail): void\n    {\n        if (strtoupper($value) !== $value) {\n            $fail('The :attribute must be uppercase.');\n        }\n    }\n}\n\n\u002F\u002F With parameters\nclass MinWords implements ValidationRule\n{\n    public function __construct(protected int $minWords) {}\n    \n    public function validate(string $attribute, mixed $value, Closure $fail): void\n    {\n        if (str_word_count($value) \u003C $this->minWords) {\n            $fail(\"The :attribute must have at least {$this->minWords} words.\");\n        }\n    }\n}\n\n\u002F\u002F Using closure rule (simple cases)\n$validator = Validator::make($request->all(), [\n    'title' => [\n        'required',\n        function (string $attribute, mixed $value, Closure $fail) {\n            if (strlen($value) \u003C 3) {\n                $fail(\"The {$attribute} is too short.\");\n            }\n        },\n    ],\n]);\n```\n\n**Using Custom Rules:**\n\n```php\nuse App\\Rules\\Uppercase;\nuse App\\Rules\\MinWords;\n\n$request->validate([\n    'code' => ['required', new Uppercase],\n    'description' => ['required', new MinWords(10)],\n    'status' => ['required', Rule::in(['active', 'inactive'])],\n]);\n```\n\n**Extending Validator (Global Rule):**\n\n```php\n\u002F\u002F AppServiceProvider\nuse Illuminate\\Support\\Facades\\Validator;\n\npublic function boot()\n{\n    Validator::extend('phone', function ($attribute, $value, $parameters, $validator) {\n        return preg_match('\u002F^[0-9]{10}$\u002F', $value);\n    });\n    \n    \u002F\u002F With custom message\n    Validator::replacer('phone', function ($message, $attribute, $rule, $parameters) {\n        return str_replace(':attribute', $attribute, 'The :attribute must be a valid 10-digit phone number.');\n    });\n}\n\n\u002F\u002F Usage\n'phone' => 'required|phone'\n```\n\n**Best Practices:**\n- Create rule classes for reusable validation\n- Use closures for one-off validation\n- Keep rules stateless when possible\n- Provide clear error messages\n\n**Follow-up Questions:**\n- How do you access other fields in custom rules?\n- Can custom rules have dependencies injected?\n- How do you test custom validation rules?",[67,151,71],"Custom Rules",{"id":153,"category":98,"question":154,"answer":155,"level":10,"tags":156},34,"What is the purpose of the `.env` file in Laravel?","The `.env` file stores environment-specific configuration variables, keeping sensitive data out of version control.\n\n**Basic Structure:**\n\n```env\nAPP_NAME=\"My Laravel App\"\nAPP_ENV=local\nAPP_KEY=base64:...\nAPP_DEBUG=true\nAPP_URL=http:\u002F\u002Flocalhost\n\nDB_CONNECTION=mysql\nDB_HOST=127.0.0.1\nDB_PORT=3306\nDB_DATABASE=laravel\nDB_USERNAME=root\nDB_PASSWORD=secret\n\nCACHE_DRIVER=file\nSESSION_DRIVER=file\nQUEUE_CONNECTION=sync\n\nMAIL_MAILER=smtp\nMAIL_HOST=smtp.mailtrap.io\nMAIL_PORT=2525\nMAIL_USERNAME=username\nMAIL_PASSWORD=password\nMAIL_ENCRYPTION=tls\n```\n\n**Accessing Variables:**\n\n```php\n\u002F\u002F Using env() helper\n$appName = env('APP_NAME');\n$debug = env('APP_DEBUG', false); \u002F\u002F With default\n\n\u002F\u002F In config files (recommended)\n\u002F\u002F config\u002Fapp.php\n'name' => env('APP_NAME', 'Laravel'),\n\n\u002F\u002F After caching config, env() returns null\n\u002F\u002F Always use config() helper in application code\n$value = config('app.name');\n```\n\n**Environment-Specific Files:**\n\n```bash\n.env               # Default\n.env.local         # Local overrides (gitignored)\n.env.production    # Production settings\n.env.testing       # Testing settings\n```\n\n**Best Practices:**\n- Never commit `.env` to version control\n- Keep a `.env.example` file for reference\n- Use different values for different environments\n- Cache config in production: `php artisan config:cache`\n- Don't use `env()` outside of config files\n\n**Security:**\n- Keep secrets (API keys, passwords) in `.env`\n- Use environment variables in CI\u002FCD\n- Rotate keys when team members leave\n\n**Follow-up Questions:**\n- What happens to `env()` after config caching?\n- How do you validate required environment variables?\n- Can you have nested environment variables?",[157,158,80],"Environment","Configuration",{"id":160,"category":98,"question":161,"answer":162,"level":10,"tags":163},35,"How do you create and use Laravel helpers?","Custom helper functions allow you to add reusable utility functions throughout your application.\n\n**Creating Helper File:**\n\n```php\n\u002F\u002F app\u002FHelpers\u002Fhelpers.php\n\nif (!function_exists('format_price')) {\n    function format_price($amount, $currency = 'USD')\n    {\n        return $currency . ' ' . number_format($amount, 2);\n    }\n}\n\nif (!function_exists('get_user_timezone')) {\n    function get_user_timezone()\n    {\n        return auth()->check() ? auth()->user()->timezone : config('app.timezone');\n    }\n}\n\nif (!function_exists('is_production')) {\n    function is_production()\n    {\n        return app()->environment('production');\n    }\n}\n```\n\n**Registering Helper File:**\n\n```php\n\u002F\u002F composer.json\n\"autoload\": {\n    \"files\": [\n        \"app\u002FHelpers\u002Fhelpers.php\"\n    ]\n}\n\n\u002F\u002F Run after adding\ncomposer dump-autoload\n```\n\n**Built-in Helpers:**\n\n```php\n\u002F\u002F Paths\n$path = public_path('css\u002Fapp.css');\n$path = storage_path('logs\u002Flaravel.log');\n$path = resource_path('views\u002Fwelcome.blade.php');\n\n\u002F\u002F Debugging\ndd($variable);\ntrace($variable);\n\n\u002F\u002F Arrays\n$array = array_wrap($value);\n$result = data_get($array, 'user.profile.name', 'default');\n$result = head($array);\n$result = last($array);\n\n\u002F\u002F Strings\n$slug = str_slug('Hello World'); \u002F\u002F 'hello-world'\n$random = str_random(32);\n$limited = str_limit($longText, 100);\n\n\u002F\u002F URLs\n$url = url('users');\n$url = secure_url('checkout');\n$asset = asset('css\u002Fapp.css');\n\n\u002F\u002F Miscellaneous\n$value = retry(5, function () {\n    \u002F\u002F Attempt operation up to 5 times\n}, 100); \u002F\u002F 100ms delay\n\n$value = tap($user, function ($user) {\n    $user->update(['last_seen' => now()]);\n}); \u002F\u002F Returns original user\n\n$value = throw_if($condition, new Exception('Error'));\n$value = throw_unless($condition, new Exception('Error'));\n```\n\n**Best Practices:**\n- Prefix functions to avoid collisions\n- Check if function exists before defining\n- Group related helpers in files\n- Document helper functions\n- Don't overuse helpers (keep logic in classes)\n\n**Follow-up Questions:**\n- What's the difference between helpers and facades?\n- How do you test custom helper functions?\n- Can helpers be autoloaded conditionally?",[164,165,166],"Helpers","Utilities","Functions",[168,179,187,193,202,210,219,225,235,244,253,261,267,273,279,286,292,299,306,313,320,328],{"id":169,"category":170,"question":171,"answer":172,"level":173,"tags":174},12,"Version Differences","What are the main differences between Laravel 8, 10, 11, and 12?","Laravel has evolved significantly across these major versions:\n\n**Laravel 8 (2020)**\n- Laravel Jetstream for auth scaffolding\n- Model factory classes\n- Migration squashing\n- Job batching\n- Improved rate limiting\n- Dynamic Blade components\n\n**Laravel 10 (2023)**\n- PHP 8.1+ minimum requirement\n- Native types everywhere\n- Laravel Pennant (feature flags)\n- Process interaction testing\n- Pest as default testing framework\n- Invokable validation rules\n\n**Laravel 11 (2024)**\n- PHP 8.2+ minimum\n- Streamlined directory structure\n- Per-second rate limiting\n- Health routing\n- Slim application skeleton\n- `bootstrap\u002Fapp.php` for middleware config\n- Dumpable trait\n- `once()` helper for memoization\n- No Kernel.php files by default\n- SQLite by default for testing\n\n**Laravel 12 (2026)**\n- PHP 8.3+ minimum\n- Enhanced type safety\n- Action classes support via Artisan\n- Improved performance (40% faster queries)\n- Better queue handling\n- Native async\u002Fawait patterns\n- AI integration helpers\n- Enhanced DDD support\n\n**Upgrading Strategies:**\n\n```bash\n# Check upgrade guides\ncomposer require laravel\u002Flegacy-factories  # For factory upgrades\n\n# Update dependencies\ncomposer update\n\n# Clear all caches\nphp artisan optimize:clear\n\n# Run upgrade checkers\ncomposer require laravel\u002Fshift\n```\n\n**Breaking Changes to Watch:**\n\n```php\n\u002F\u002F Laravel 10 to 11\n\u002F\u002F Before (Laravel 10) - Kernel files in app\u002FHttp\n\u002F\u002F After (Laravel 11) - Configuration in bootstrap\u002Fapp.php\n\n\u002F\u002F Before\nclass Kernel extends HttpKernel\n{\n    protected $middleware = [\n        TrustProxies::class,\n    ];\n}\n\n\u002F\u002F After (bootstrap\u002Fapp.php)\n->withMiddleware(function (Middleware $middleware) {\n    $middleware->append(TrustProxies::class);\n})\n\n\u002F\u002F Factory changes\n\u002F\u002F Before (Laravel 8)\n$factory->define(User::class, function ($faker) {\n    return [];\n});\n\n\u002F\u002F After (Laravel 9+)\nclass UserFactory extends Factory\n{\n    public function definition()\n    {\n        return [];\n    }\n}\n```\n\n**Migration Tips:**\n- Always check deprecation logs\n- Update composer.json PHP version\n- Run `php artisan optimize:clear`\n- Update third-party packages\n- Test thoroughly before production deployment\n- Use Laravel Shift for automated upgrades\n\n**Performance Improvements:**\n- Laravel 12: 40% faster query execution\n- Laravel 11: Reduced bootstrap time\n- Laravel 10: Improved memory usage\n- All versions: Better caching mechanisms\n\n**Follow-up Questions:**\n- How do you handle major version upgrades in production?\n- What's the upgrade path from Laravel 8 to 12?\n- Which version should you choose for new projects?","intermediate",[175,176,177,178],"Versions","Laravel 12","Migration","Upgrade",{"id":180,"category":79,"question":181,"answer":182,"level":173,"tags":183},13,"What are Authentication Guards and how do you use them?","Guards define how users are authenticated for each request in Laravel.\n\n**Built-in Guards:**\n- `session` - Traditional session-based auth (web)\n- `token` - API token authentication (legacy)\n- `sanctum` - API tokens for SPAs\u002Fmobile\n- `passport` - OAuth2 implementation\n\n**Configuration (config\u002Fauth.php):**\n\n```php\n'guards' => [\n    'web' => [\n        'driver' => 'session',\n        'provider' => 'users',\n    ],\n    'api' => [\n        'driver' => 'token',\n        'provider' => 'users',\n        'hash' => false,\n    ],\n    'admin' => [\n        'driver' => 'session',\n        'provider' => 'admins',\n    ],\n    'customer' => [\n        'driver' => 'sanctum',\n        'provider' => 'customers',\n    ],\n],\n\n'providers' => [\n    'users' => [\n        'driver' => 'eloquent',\n        'model' => App\\Models\\User::class,\n    ],\n    'admins' => [\n        'driver' => 'eloquent',\n        'model' => App\\Models\\Admin::class,\n    ],\n    'customers' => [\n        'driver' => 'eloquent',\n        'model' => App\\Models\\Customer::class,\n    ],\n],\n```\n\n**Using Multiple Guards:**\n\n```php\n\u002F\u002F Default guard\nAuth::check();\nAuth::user();\nAuth::id();\n\n\u002F\u002F Specific guard\nAuth::guard('admin')->check();\nAuth::guard('admin')->user();\nAuth::guard('api')->user();\n\n\u002F\u002F Login with specific guard\nAuth::guard('admin')->attempt([\n    'email' => $request->email,\n    'password' => $request->password,\n]);\n\n\u002F\u002F Logout from specific guard\nAuth::guard('admin')->logout();\n\n\u002F\u002F Get guard instance\n$guard = Auth::guard('admin');\n$user = $guard->user();\n```\n\n**Route Middleware with Guards:**\n\n```php\n\u002F\u002F Single guard\nRoute::get('\u002Fadmin\u002Fdashboard', function () {\n    \u002F\u002F\n})->middleware('auth:admin');\n\n\u002F\u002F Multiple guards (any works)\nRoute::get('\u002Fdashboard', function () {\n    \u002F\u002F\n})->middleware('auth:web,admin');\n\n\u002F\u002F Group middleware\nRoute::middleware(['auth:admin'])->group(function () {\n    Route::get('\u002Fadmin\u002Fusers', [AdminController::class, 'users']);\n    Route::get('\u002Fadmin\u002Fsettings', [AdminController::class, 'settings']);\n});\n\n\u002F\u002F Controller middleware\nclass AdminController extends Controller\n{\n    public function __construct()\n    {\n        $this->middleware('auth:admin');\n        $this->middleware('auth:api')->only('api');\n    }\n}\n```\n\n**Custom Guard Driver:**\n\n```php\n\u002F\u002F In AppServiceProvider\nuse Illuminate\\Support\\Facades\\Auth;\nuse App\\Guards\\JwtGuard;\n\npublic function boot()\n{\n    Auth::extend('jwt', function ($app, $name, array $config) {\n        return new JwtGuard(\n            Auth::createUserProvider($config['provider']),\n            $app['request'],\n            $config\n        );\n    });\n}\n\n\u002F\u002F Custom guard implementation\nclass JwtGuard implements Guard\n{\n    protected $user;\n    protected $provider;\n    protected $request;\n\n    public function __construct($provider, $request, $config)\n    {\n        $this->provider = $provider;\n        $this->request = $request;\n    }\n\n    public function user()\n    {\n        if ($this->user !== null) {\n            return $this->user;\n        }\n\n        $token = $this->getTokenFromRequest();\n        if ($token) {\n            $payload = JWT::decode($token);\n            $this->user = $this->provider->retrieveById($payload->sub);\n        }\n\n        return $this->user;\n    }\n\n    public function validate(array $credentials = [])\n    {\n        $user = $this->provider->retrieveByCredentials($credentials);\n        return $user && $this->provider->validateCredentials($user, $credentials);\n    }\n\n    public function setUser($user)\n    {\n        $this->user = $user;\n        return $this;\n    }\n\n    private function getTokenFromRequest()\n    {\n        return $this->request->bearerToken();\n    }\n}\n```\n\n**Sanctum vs Passport:**\n\n```php\n\u002F\u002F Sanctum - Simpler, for SPAs and mobile\n\u002F\u002F Installation\ncomposer require laravel\u002Fsanctum\nphp artisan vendor:publish --provider=\"Laravel\\Sanctum\\SanctumServiceProvider\"\nphp artisan migrate\n\n\u002F\u002F Generate token\n$token = $user->createToken('api-token')->plainTextToken;\n\n\u002F\u002F Verify token\n$user = Auth::guard('sanctum')->user();\n\n\u002F\u002F Passport - Full OAuth2 server\ncomposer require laravel\u002Fpassport\nphp artisan passport:install\nphp artisan passport:client --password\n\n\u002F\u002F Generate token via OAuth2\n$response = Http::asForm()->post('http:\u002F\u002Fyour-app.com\u002Foauth\u002Ftoken', [\n    'grant_type' => 'password',\n    'client_id' => 'client-id',\n    'client_secret' => 'client-secret',\n    'username' => 'user@example.com',\n    'password' => 'password',\n    'scope' => '',\n]);\n```\n\n**Creating Custom Providers:**\n\n```php\n\u002F\u002F Custom user provider\nclass CustomUserProvider implements UserProvider\n{\n    public function retrieveById($identifier) {}\n    public function retrieveByToken($identifier, $token) {}\n    public function updateRememberToken(Authenticatable $user, $token) {}\n    public function retrieveByCredentials(array $credentials) {}\n    public function validateCredentials(Authenticatable $user, array $credentials) {}\n}\n\n\u002F\u002F Register provider\nAuth::provider('custom', function ($app, array $config) {\n    return new CustomUserProvider();\n});\n```\n\n**Practical Multi-Auth Example:**\n\n```php\n\u002F\u002F User login for web\nclass LoginController\n{\n    public function login(Request $request)\n    {\n        if (Auth::guard('web')->attempt($request->only('email', 'password'))) {\n            return redirect('\u002Fdashboard');\n        }\n        return back()->withErrors(['email' => 'Invalid credentials']);\n    }\n}\n\n\u002F\u002F Admin login\nclass AdminLoginController\n{\n    public function login(Request $request)\n    {\n        if (Auth::guard('admin')->attempt($request->only('email', 'password'))) {\n            return redirect('\u002Fadmin\u002Fdashboard');\n        }\n        return back()->withErrors(['email' => 'Invalid admin credentials']);\n    }\n}\n\n\u002F\u002F Get current guards\npublic function currentUser(Request $request)\n{\n    if ($request->user('admin')) {\n        return response()->json(['type' => 'admin', 'user' => $request->user('admin')]);\n    }\n    \n    if ($request->user()) {\n        return response()->json(['type' => 'user', 'user' => $request->user()]);\n    }\n    \n    return response()->json(['type' => 'guest']);\n}\n```\n\n**Security Best Practices:**\n- Use different session domains for different guards\n- Implement rate limiting on authentication attempts\n- Use HTTPS in production\n- Rotate API tokens regularly\n- Implement logout for all guards\n\n**Performance Considerations:**\n- Cache user data when using token-based auth\n- Use database sessions for multi-server setups\n- Implement token revocation for security\n\n**Common Mistakes:**\n- Mixing guard contexts\n- Not handling guard-specific middleware\n- Forgetting to configure providers\n- Using same session for different guards\n- Not implementing guard-specific logout\n\n**Follow-up Questions:**\n- How do you implement SSO with guards?\n- What's the difference between provider and guard?\n- How do you handle user impersonation with multiple guards?\n- Can guards share the same user provider?",[184,79,80,185,186],"Guards","Sanctum","Passport",{"id":188,"category":87,"question":189,"answer":190,"level":173,"tags":191},14,"What was the role of Kernel.php and how has it changed in Laravel 11+?","Kernel.php was the central place for middleware and scheduling configuration before Laravel 11.\n\n**Laravel 10 and Earlier:**\n\n```php\n\u002F\u002F app\u002FHttp\u002FKernel.php\nclass Kernel extends HttpKernel\n{\n    \u002F\u002F Global middleware (every request)\n    protected $middleware = [\n        \\App\\Http\\Middleware\\TrustProxies::class,\n        \\App\\Http\\Middleware\\HandleCors::class,\n        \\App\\Http\\Middleware\\PreventRequestsDuringMaintenance::class,\n        \\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize::class,\n        \\App\\Http\\Middleware\\TrimStrings::class,\n        \\Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull::class,\n    ];\n\n    \u002F\u002F Middleware groups\n    protected $middlewareGroups = [\n        'web' => [\n            \\App\\Http\\Middleware\\EncryptCookies::class,\n            \\Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse::class,\n            \\Illuminate\\Session\\Middleware\\StartSession::class,\n            \\Illuminate\\View\\Middleware\\ShareErrorsFromSession::class,\n            \\App\\Http\\Middleware\\VerifyCsrfToken::class,\n            \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n        ],\n\n        'api' => [\n            \\Illuminate\\Routing\\Middleware\\ThrottleRequests::class . ':api',\n            \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n        ],\n    ];\n\n    \u002F\u002F Route middleware aliases\n    protected $middlewareAliases = [\n        'auth' => \\App\\Http\\Middleware\\Authenticate::class,\n        'auth.basic' => \\Illuminate\\Auth\\Middleware\\AuthenticateWithBasicAuth::class,\n        'auth.session' => \\Illuminate\\Session\\Middleware\\AuthenticateSession::class,\n        'cache.headers' => \\Illuminate\\Http\\Middleware\\SetCacheHeaders::class,\n        'can' => \\Illuminate\\Auth\\Middleware\\Authorize::class,\n        'guest' => \\App\\Http\\Middleware\\RedirectIfAuthenticated::class,\n        'password.confirm' => \\Illuminate\\Auth\\Middleware\\RequirePassword::class,\n        'precognitive' => \\Illuminate\\Foundation\\Http\\Middleware\\HandlePrecognitiveRequests::class,\n        'signed' => \\App\\Http\\Middleware\\ValidateSignature::class,\n        'throttle' => \\Illuminate\\Routing\\Middleware\\ThrottleRequests::class,\n        'verified' => \\Illuminate\\Auth\\Middleware\\EnsureEmailIsVerified::class,\n    ];\n\n    \u002F\u002F Priority order\n    protected $middlewarePriority = [\n        \\Illuminate\\Foundation\\Http\\Middleware\\HandlePrecognitiveRequests::class,\n        \\Illuminate\\Cookie\\Middleware\\EncryptCookies::class,\n        \\Illuminate\\Session\\Middleware\\StartSession::class,\n        \\Illuminate\\View\\Middleware\\ShareErrorsFromSession::class,\n        \\Illuminate\\Contracts\\Auth\\Middleware\\AuthenticatesRequests::class,\n        \\Illuminate\\Routing\\Middleware\\ThrottleRequests::class,\n        \\Illuminate\\Routing\\Middleware\\ThrottleRequestsWithRedis::class,\n        \\Illuminate\\Session\\Middleware\\AuthenticateSession::class,\n        \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n        \\Illuminate\\Auth\\Middleware\\Authorize::class,\n    ];\n}\n\n\u002F\u002F app\u002FConsole\u002FKernel.php\nclass Kernel extends ConsoleKernel\n{\n    protected function schedule(Schedule $schedule)\n    {\n        $schedule->command('inspire')->hourly();\n        $schedule->command('emails:send')->dailyAt('08:00');\n        $schedule->exec('node script.js')->everyMinute();\n    }\n\n    protected function commands()\n    {\n        $this->load(__DIR__.'\u002FCommands');\n        require base_path('routes\u002Fconsole.php');\n    }\n}\n```\n\n**Laravel 11+ (Simplified):**\n\n```php\n\u002F\u002F bootstrap\u002Fapp.php\nuse Illuminate\\Foundation\\Application;\nuse Illuminate\\Foundation\\Configuration\\Exceptions;\nuse Illuminate\\Foundation\\Configuration\\Middleware;\nuse Illuminate\\Console\\Scheduling\\Schedule;\n\nreturn Application::configure(basePath: dirname(__DIR__))\n    ->withRouting(\n        web: __DIR__.'\u002F..\u002Froutes\u002Fweb.php',\n        api: __DIR__.'\u002F..\u002Froutes\u002Fapi.php',\n        commands: __DIR__.'\u002F..\u002Froutes\u002Fconsole.php',\n        health: '\u002Fup',\n    )\n    ->withMiddleware(function (Middleware $middleware) {\n        \u002F\u002F Global middleware\n        $middleware->append([\n            \\App\\Http\\Middleware\\TrustProxies::class,\n            \\App\\Http\\Middleware\\HandleCors::class,\n        ]);\n\n        \u002F\u002F Add to web group\n        $middleware->web(append: [\n            \\App\\Http\\Middleware\\CustomWebMiddleware::class,\n        ]);\n\n        \u002F\u002F Add to api group\n        $middleware->api(prepend: [\n            \\App\\Http\\Middleware\\ForceJsonResponse::class,\n        ]);\n\n        \u002F\u002F Middleware aliases\n        $middleware->alias([\n            'admin' => \\App\\Http\\Middleware\\EnsureUserIsAdmin::class,\n            '2fa' => \\App\\Http\\Middleware\\TwoFactorAuthentication::class,\n        ]);\n\n        \u002F\u002F Priority\n        $middleware->priority([\n            \\Illuminate\\Foundation\\Http\\Middleware\\HandlePrecognitiveRequests::class,\n            \\Illuminate\\Cookie\\Middleware\\EncryptCookies::class,\n        ]);\n\n        \u002F\u002F Remove default middleware\n        $middleware->web(remove: [\n            \\App\\Http\\Middleware\\VerifyCsrfToken::class,\n        ]);\n    })\n    ->withExceptions(function (Exceptions $exceptions) {\n        $exceptions->render(function (\\App\\Exceptions\\CustomException $e, $request) {\n            return response()->json(['error' => $e->getMessage()], 500);\n        });\n\n        $exceptions->reportable(function (\\Throwable $e) {\n            if ($e->getCode() === 429) {\n                Log::warning('Rate limit exceeded', ['url' => request()->url()]);\n            }\n        });\n    })\n    ->withSchedule(function (Schedule $schedule) {\n        $schedule->command('inspire')->hourly();\n        $schedule->command('emails:send')->dailyAt('08:00');\n        $schedule->exec('node script.js')->everyMinute();\n\n        \u002F\u002F Task hooks\n        $schedule->job(new ProcessPodcast)->daily();\n\n        \u002F\u002F Environments\n        $schedule->command('backup:run')\n            ->daily()\n            ->environments(['production']);\n\n        \u002F\u002F Maintenance\n        $schedule->command('horizon:snapshot')->everyFiveMinutes();\n    })\n    ->withProviders([\n        App\\Providers\\CustomServiceProvider::class,\n    ])\n    ->create();\n```\n\n**Key Changes:**\n- No separate Kernel classes by default\n- All configuration in `bootstrap\u002Fapp.php`\n- Fluent API for middleware and exceptions\n- Slimmer application skeleton\n- Better discoverability\n- Reduced boilerplate code\n\n**Migration Strategy:**\n\n```php\n\u002F\u002F Step 1: Create bootstrap\u002Fapp.php with your configuration\n\u002F\u002F Step 2: Move middleware from Kernel.php\n\u002F\u002F Step 3: Move schedule from Console\\Kernel.php\n\u002F\u002F Step 4: Move exception handling from Handler.php\n\u002F\u002F Step 5: Test thoroughly\n\u002F\u002F Step 6: Remove old Kernel files (optional, they still work)\n\n\u002F\u002F Custom kernel still works in Laravel 11\nclass Kernel extends HttpKernel\n{\n    \u002F\u002F This will still be respected\n    protected $middleware = [\n        \u002F\u002F\n    ];\n}\n```\n\n**Benefits of New Approach:**\n1. **Simpler Configuration**: Everything in one place\n2. **Better Type Safety**: IDE autocomplete for methods\n3. **Easier Testing**: Configuration can be modified in tests\n4. **Reduced Boilerplate**: No need for multiple kernel classes\n5. **Clearer Organization**: All bootstrapping in one file\n\n**Performance Impact:**\n- Slightly faster bootstrap (less class loading)\n- Same runtime performance\n- Improved memory usage\n\n**Common Migration Issues:**\n- Missing middleware after upgrade\n- Schedule commands not running\n- Exception handling differences\n- Service provider registration order\n\n**Testing the New Configuration:**\n\n```php\n\u002F\u002F Test middleware registration\npublic function test_custom_middleware_is_registered()\n{\n    $middleware = app()->make(Middleware::class);\n    $this->assertArrayHasKey('admin', $middleware->getAliases());\n}\n\n\u002F\u002F Test schedule\npublic function test_schedule_is_configured()\n{\n    $schedule = app()->make(Schedule::class);\n    $events = $schedule->events();\n    $this->assertNotEmpty($events);\n}\n```\n\n**Follow-up Questions:**\n- Why was the Kernel removed in Laravel 11?\n- How do you add custom middleware groups?\n- Can you still use Kernel.php in Laravel 11?\n- How does the new approach affect performance?",[87,192,158,35],"Laravel 11",{"id":194,"category":195,"question":196,"answer":197,"level":173,"tags":198},15,"Service Container","Explain Laravel's Service Container and dependency injection.","The Service Container is the heart of Laravel's IoC (Inversion of Control) system for managing class dependencies.\n\n**What is it?**\nA powerful tool for managing class dependencies and performing dependency injection automatically.\n\n**Basic Binding:**\n\n```php\n\u002F\u002F Simple binding (new instance each time)\n$this->app->bind(PaymentGateway::class, StripePaymentGateway::class);\n\n\u002F\u002F Singleton (single instance shared)\n$this->app->singleton(Logger::class, function ($app) {\n    return new FileLogger($app['config']['logging.path']);\n});\n\n\u002F\u002F Instance binding (already resolved)\n$this->app->instance(Config::class, $configInstance);\n\n\u002F\u002F Bind interface to implementation\n$this->app->bind(\n    UserRepositoryInterface::class,\n    EloquentUserRepository::class\n);\n```\n\n**Contextual Binding:**\n\n```php\n\u002F\u002F Different implementations for different classes\n$this->app->when(PhotoController::class)\n    ->needs(Filesystem::class)\n    ->give(function () {\n        return Storage::disk('photos');\n    });\n\n$this->app->when(VideoController::class)\n    ->needs(Filesystem::class)\n    ->give(function () {\n        return Storage::disk('videos');\n    });\n\n\u002F\u002F Primitive values\n$this->app->when(ReportGenerator::class)\n    ->needs('$format')\n    ->give('pdf');\n\n\u002F\u002F Tagged services\n$this->app->tag([SpamReport::class, FraudReport::class], 'reports');\n\n$this->app->bind(ReportAggregator::class, function ($app) {\n    return new ReportAggregator($app->tagged('reports'));\n});\n```\n\n**Resolving Dependencies:**\n\n```php\n\u002F\u002F Using app() helper\n$gateway = app(PaymentGateway::class);\n\n\u002F\u002F Using make()\n$gateway = $this->app->make(PaymentGateway::class);\n\n\u002F\u002F With parameters\n$api = $this->app->make(ApiClient::class, [\n    'apiKey' => config('services.api.key')\n]);\n\n\u002F\u002F Automatic injection in controllers\nclass OrderController\n{\n    public function __construct(\n        private PaymentGateway $gateway,\n        private Logger $logger\n    ) {}\n\n    public function store(Request $request)\n    {\n        \u002F\u002F $this->gateway is automatically injected\n    }\n}\n\n\u002F\u002F Method injection\nclass ReportController\n{\n    public function generate(Request $request, ReportGenerator $generator)\n    {\n        return $generator->make($request->all());\n    }\n}\n```\n\n**Advanced Binding Patterns:**\n\n```php\n\u002F\u002F Binding with closure\n$this->app->bind('payment', function ($app) {\n    return new PaymentGateway(\n        $app['config']['payment.key'],\n        $app['config']['payment.secret']\n    );\n});\n\n\u002F\u002F Binding with factory\n$this->app->bind(PaymentGateway::class, function ($app) {\n    $factory = new PaymentGatewayFactory();\n    return $factory->make(\n        $app['config']['payment.driver']\n    );\n});\n\n\u002F\u002F Extending bindings\n$this->app->extend(Logger::class, function ($logger, $app) {\n    return $logger->withContext([\n        'request_id' => Str::uuid()\n    ]);\n});\n```\n\n**Service Provider Integration:**\n\n```php\nnamespace App\\Providers;\n\nuse App\\Services\\PaymentGateway;\nuse App\\Services\\StripeGateway;\nuse Illuminate\\Support\\ServiceProvider;\n\nclass PaymentServiceProvider extends ServiceProvider\n{\n    public function register(): void\n    {\n        $this->app->singleton(PaymentGateway::class, function ($app) {\n            return new StripeGateway(\n                config('services.stripe.key'),\n                config('services.stripe.webhook_secret')\n            );\n        });\n\n        \u002F\u002F Deferred provider\n        if ($this->app->runningInConsole()) {\n            $this->commands([\n                PaymentSyncCommand::class,\n            ]);\n        }\n    }\n\n    public function boot(): void\n    {\n        \u002F\u002F After all providers registered\n        $gateway = $this->app->make(PaymentGateway::class);\n        $gateway->initialize();\n    }\n}\n```\n\n**Testing with Container:**\n\n```php\n\u002F\u002F Swap implementation in tests\n$this->app->instance(\n    PaymentGateway::class,\n    Mockery::mock(PaymentGateway::class)\n);\n\n\u002F\u002F Bind for specific test\n$this->app->bind(PaymentGateway::class, function () {\n    $mock = Mockery::mock(PaymentGateway::class);\n    $mock->shouldReceive('charge')->once()->andReturn(true);\n    return $mock;\n});\n```\n\n**Common Patterns:**\n\n```php\n\u002F\u002F Repository pattern with container\n$this->app->bind(UserRepository::class, function ($app) {\n    return new EloquentUserRepository(\n        $app['db.connection'],\n        $app['events']\n    );\n});\n\n\u002F\u002F Factory pattern\n$this->app->bind(NotificationFactory::class, function ($app) {\n    return new NotificationFactory([\n        'email' => EmailNotification::class,\n        'sms' => SmsNotification::class,\n        'push' => PushNotification::class,\n    ]);\n});\n\n\u002F\u002F Multi-tenant binding\n$this->app->bind(DatabaseConnection::class, function ($app) {\n    $tenant = $app['request']->get('tenant');\n    return new TenantConnection($tenant);\n});\n```\n\n**Container Events:**\n\n```php\n\u002F\u002F Resolving event\n$this->app->resolving(PaymentGateway::class, function ($gateway, $app) {\n    $gateway->setLogger($app['log']);\n});\n\n\u002F\u002F After resolving any object\n$this->app->afterResolving(function ($object, $app) {\n    if (method_exists($object, 'initialize')) {\n        $object->initialize();\n    }\n});\n```\n\n**Performance Tips:**\n- Use `singleton()` for stateless services\n- Use `bind()` for factories and new instances per request\n- Defer heavy service providers\n- Cache container bindings in production\n\n**Common Mistakes:**\n- Circular dependencies\n- Binding too many singletons\n- Forgetting to register providers\n- Using container as service locator\n- Not using interfaces for bindings\n\n**Benefits:**\n- Loose coupling\n- Easy testing with mocks\n- Flexible configuration\n- Automatic resolution\n- Centralized dependency management\n\n**Follow-up Questions:**\n- What's the difference between `bind` and `singleton`?\n- How does automatic dependency resolution work?\n- When would you use contextual binding?\n- How do you test classes that use the container?",[195,199,200,201],"IoC","Dependency Injection","Binding",{"id":203,"category":204,"question":205,"answer":206,"level":173,"tags":207},16,"Service Providers","What are Service Providers and how do they work?","Service Providers are the central place for bootstrapping Laravel applications and registering services.\n\n**Purpose:**\n- Register bindings in the service container\n- Register event listeners, middleware, routes\n- Perform bootstrap tasks\n- Configure packages\n\n**Creating a Service Provider:**\n\n```bash\nphp artisan make:provider PaymentServiceProvider\nphp artisan make:provider EventServiceProvider --event\n```\n\n**Basic Provider Structure:**\n\n```php\nnamespace App\\Providers;\n\nuse Illuminate\\Support\\ServiceProvider;\nuse App\\Services\\PaymentGateway;\nuse App\\Services\\StripeGateway;\n\nclass PaymentServiceProvider extends ServiceProvider\n{\n    \u002F**\n     * Register services - bindings, singletons\n     * No access to other services yet\n     *\u002F\n    public function register(): void\n    {\n        \u002F\u002F Simple binding\n        $this->app->bind(PaymentGateway::class, StripeGateway::class);\n\n        \u002F\u002F Singleton with closure\n        $this->app->singleton('payment', function ($app) {\n            return new StripeGateway(\n                $app['config']['services.stripe.key'],\n                $app['config']['services.stripe.secret']\n            );\n        });\n\n        \u002F\u002F Merge configuration\n        $this->mergeConfigFrom(\n            __DIR__.'\u002F..\u002Fconfig\u002Fpayment.php', 'payment'\n        );\n\n        \u002F\u002F Register commands\n        $this->commands([\n            \\App\\Console\\Commands\\SyncPayments::class,\n        ]);\n    }\n\n    \u002F**\n     * Bootstrap services - after all providers registered\n     * Can use other services and facades here\n     *\u002F\n    public function boot(): void\n    {\n        \u002F\u002F Load routes\n        $this->loadRoutesFrom(__DIR__.'\u002F..\u002Froutes\u002Fpayment.php');\n\n        \u002F\u002F Load views\n        $this->loadViewsFrom(__DIR__.'\u002F..\u002Fviews\u002Fpayment', 'payment');\n\n        \u002F\u002F Load translations\n        $this->loadTranslationsFrom(__DIR__.'\u002F..\u002Flang\u002Fpayment', 'payment');\n\n        \u002F\u002F Load migrations\n        $this->loadMigrationsFrom(__DIR__.'\u002F..\u002Fdatabase\u002Fmigrations');\n\n        \u002F\u002F Publish assets\n        $this->publishes([\n            __DIR__.'\u002F..\u002Fconfig\u002Fpayment.php' => config_path('payment.php'),\n            __DIR__.'\u002F..\u002Fviews' => resource_path('views\u002Fvendor\u002Fpayment'),\n        ], 'payment-assets');\n\n        \u002F\u002F Register view composer\n        view()->composer('payment::form', function ($view) {\n            $view->with('paymentMethods', PaymentMethod::all());\n        });\n\n        \u002F\u002F Register middleware\n        $this->app['router']->aliasMiddleware('payment.auth', \\App\\Http\\Middleware\\PaymentAuth::class);\n\n        \u002F\u002F Register event listeners\n        Event::listen(PaymentProcessed::class, SendPaymentReceipt::class);\n    }\n}\n```\n\n**Deferred Providers:**\n\n```php\nuse Illuminate\\Contracts\\Support\\DeferrableProvider;\n\nclass HeavyServiceProvider extends ServiceProvider implements DeferrableProvider\n{\n    public function register(): void\n    {\n        $this->app->singleton(HeavyService::class, function ($app) {\n            return new HeavyService(\n                $app['config']['heavy.timeout'],\n                $app['cache']\n            );\n        });\n    }\n\n    \u002F\u002F Specify which services this provider registers\n    public function provides(): array\n    {\n        return [HeavyService::class];\n    }\n}\n\n\u002F\u002F The provider will only be loaded when HeavyService is resolved\n```\n\n**Provider Registration:**\n\n```php\n\u002F\u002F Laravel 11+ - bootstrap\u002Fproviders.php\nreturn [\n    App\\Providers\\AppServiceProvider::class,\n    App\\Providers\\EventServiceProvider::class,\n    App\\Providers\\PaymentServiceProvider::class,\n    App\\Providers\\RouteServiceProvider::class,\n];\n\n\u002F\u002F Or in bootstrap\u002Fapp.php\n->withProviders([\n    App\\Providers\\CustomServiceProvider::class,\n])\n```\n\n**Event Service Provider:**\n\n```php\nclass EventServiceProvider extends ServiceProvider\n{\n    protected $listen = [\n        Registered::class => [\n            SendEmailVerificationNotification::class,\n        ],\n        OrderPlaced::class => [\n            UpdateInventory::class,\n            SendOrderConfirmation::class,\n            ProcessPayment::class,\n        ],\n    ];\n\n    protected $subscribe = [\n        UserEventSubscriber::class,\n    ];\n\n    public function boot(): void\n    {\n        parent::boot();\n\n        \u002F\u002F Register custom events\n        Event::listen('*', function ($eventName, $data) {\n            Log::debug('Event fired: ' . $eventName);\n        });\n    }\n}\n```\n\n**Route Service Provider:**\n\n```php\nclass RouteServiceProvider extends ServiceProvider\n{\n    public const HOME = '\u002Fdashboard';\n\n    public function boot(): void\n    {\n        $this->configureRateLimiting();\n\n        $this->routes(function () {\n            Route::middleware('api')\n                ->prefix('api')\n                ->group(base_path('routes\u002Fapi.php'));\n\n            Route::middleware('web')\n                ->group(base_path('routes\u002Fweb.php'));\n        });\n    }\n\n    protected function configureRateLimiting(): void\n    {\n        RateLimiter::for('api', function (Request $request) {\n            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());\n        });\n    }\n}\n```\n\n**Custom Provider with Package Development:**\n\n```php\nclass AnalyticsServiceProvider extends ServiceProvider\n{\n    public function register(): void\n    {\n        $this->mergeConfigFrom(\n            __DIR__.'\u002F..\u002Fconfig\u002Fanalytics.php', 'analytics'\n        );\n\n        $this->app->singleton(Analytics::class, function ($app) {\n            return new Analytics(\n                $app['config']['analytics.tracking_id'],\n                $app['request']\n            );\n        });\n    }\n\n    public function boot(): void\n    {\n        if ($this->app->runningInConsole()) {\n            $this->publishes([\n                __DIR__.'\u002F..\u002Fconfig\u002Fanalytics.php' => config_path('analytics.php'),\n            ], 'analytics-config');\n\n            $this->publishes([\n                __DIR__.'\u002F..\u002Fdatabase\u002Fmigrations\u002F' => database_path('migrations'),\n            ], 'analytics-migrations');\n        }\n\n        $this->loadViewsFrom(__DIR__.'\u002F..\u002Fresources\u002Fviews', 'analytics');\n\n        $this->loadRoutesFrom(__DIR__.'\u002F..\u002Froutes\u002Fweb.php');\n    }\n}\n```\n\n**Lifecycle Hooks:**\n\n```php\nclass CustomServiceProvider extends ServiceProvider\n{\n    public function register(): void\n    {\n        \u002F\u002F Called first\n        $this->app->bind(Service::class, ConcreteService::class);\n    }\n\n    public function boot(): void\n    {\n        \u002F\u002F Called after all providers registered\n        \u002F\u002F All services available\n    }\n\n    \u002F\u002F For deferred providers\n    public function provides(): array\n    {\n        return [Service::class];\n    }\n\n    \u002F\u002F Check if provider is deferred\n    public function isDeferred(): bool\n    {\n        return true;\n    }\n}\n```\n\n**Testing Providers:**\n\n```php\npublic function test_service_provider_registers_bindings()\n{\n    $provider = new PaymentServiceProvider(app());\n    $provider->register();\n\n    $this->assertTrue(app()->bound(PaymentGateway::class));\n    $this->assertInstanceOf(\n        StripeGateway::class,\n        app(PaymentGateway::class)\n    );\n}\n```\n\n**Best Practices:**\n- Keep `register()` method lightweight\n- Use `boot()` for actions that need other services\n- Use deferred providers for heavy services\n- Always publish config files for packages\n- Register commands in `register()` method\n- Use `mergeConfigFrom()` for config defaults\n\n**Common Mistakes:**\n- Using services in `register()` method\n- Forgetting to register providers\n- Not handling service dependencies\n- Overloading providers with too many responsibilities\n- Registering the same binding multiple times\n\n**Performance Tips:**\n- Defer providers that aren't always needed\n- Cache provider registration in production\n- Avoid heavy operations in provider boot\n- Use lazy loading for service bindings\n\n**Follow-up Questions:**\n- What's the difference between `register()` and `boot()`?\n- When should you use deferred providers?\n- How do service providers affect application performance?\n- Can you have conditional provider registration?",[204,208,20,209],"Bootstrapping","Packages",{"id":211,"category":212,"question":213,"answer":214,"level":173,"tags":215},17,"Facades","How do Laravel Facades work under the hood?","Facades provide a static interface to services in the container, acting as static proxies to underlying instances.\n\n**How They Work:**\n\n```php\nuse Illuminate\\Support\\Facades\\Cache;\n\nCache::get('key');\n\n\u002F\u002F Is equivalent to:\napp('cache')->get('key');\n\n\u002F\u002F The magic happens in __callStatic\n```\n\n**Behind the Scenes:**\n\n```php\nabstract class Facade\n{\n    protected static $app;\n    protected static $resolvedInstance;\n\n    public static function __callStatic($method, $args)\n    {\n        $instance = static::getFacadeRoot();\n\n        if (! $instance) {\n            throw new RuntimeException('Facade root not set');\n        }\n\n        return $instance->$method(...$args);\n    }\n\n    protected static function getFacadeRoot()\n    {\n        return static::resolveFacadeInstance(static::getFacadeAccessor());\n    }\n\n    protected static function resolveFacadeInstance($name)\n    {\n        if (isset(static::$resolvedInstance[$name])) {\n            return static::$resolvedInstance[$name];\n        }\n\n        return static::$resolvedInstance[$name] = static::$app[$name];\n    }\n\n    protected static function getFacadeAccessor()\n    {\n        throw new RuntimeException('Facade does not implement getFacadeAccessor method');\n    }\n\n    \u002F\u002F Swap the underlying instance (for testing)\n    public static function swap($instance)\n    {\n        static::$resolvedInstance[static::getFacadeAccessor()] = $instance;\n\n        if (isset(static::$app)) {\n            static::$app->instance(static::getFacadeAccessor(), $instance);\n        }\n    }\n}\n\n\u002F\u002F Example facade\nclass Cache extends Facade\n{\n    protected static function getFacadeAccessor()\n    {\n        return 'cache'; \u002F\u002F Container binding key\n    }\n}\n```\n\n**Creating Custom Facades:**\n\n```php\nnamespace App\\Facades;\n\nuse Illuminate\\Support\\Facades\\Facade;\n\nclass Payment extends Facade\n{\n    protected static function getFacadeAccessor(): string\n    {\n        return 'payment'; \u002F\u002F Key in container\n    }\n}\n\n\u002F\u002F Register in ServiceProvider\nclass PaymentServiceProvider extends ServiceProvider\n{\n    public function register(): void\n    {\n        $this->app->singleton('payment', function ($app) {\n            return new PaymentGateway(\n                $app['config']['payment.api_key'],\n                $app['config']['payment.secret']\n            );\n        });\n    }\n}\n\n\u002F\u002F Usage\nuse App\\Facades\\Payment;\n\nPayment::charge(100, 'usd');\n```\n\n**Real-Time Facades:**\n\n```php\n\u002F\u002F Without facade\nuse App\\Services\\PaymentService;\n\nclass OrderController\n{\n    public function __construct(\n        private PaymentService $payment\n    ) {}\n\n    public function store()\n    {\n        $this->payment->process();\n    }\n}\n\n\u002F\u002F With real-time facade\nuse Facades\\App\\Services\\PaymentService;\n\nclass OrderController\n{\n    public function store()\n    {\n        PaymentService::process();\n    }\n}\n\n\u002F\u002F Laravel generates facade dynamically\n```\n\n**Testing with Facades:**\n\n```php\nuse Illuminate\\Support\\Facades\\Cache;\n\npublic function test_cache_usage()\n{\n    \u002F\u002F Mock facade\n    Cache::shouldReceive('get')\n        ->once()\n        ->with('user:1')\n        ->andReturn(['name' => 'John']);\n\n    Cache::shouldReceive('put')\n        ->once()\n        ->with('user:1', ['name' => 'John'], 3600);\n\n    $response = $this->get('\u002Fuser\u002F1');\n    $response->assertStatus(200);\n}\n\n\u002F\u002F Partial mock\nCache::partialMock();\nCache::shouldReceive('get')->andReturn('cached value');\n\n\u002F\u002F Spy\nCache::spy();\n\u002F\u002F Perform operations\nCache::shouldHaveReceived('put')->once();\n```\n\n**Facade vs Dependency Injection:**\n\n```php\n\u002F\u002F Using Facade\nclass OrderController\n{\n    public function store()\n    {\n        Log::info('Processing order');\n        Cache::put('last_order', $order->id);\n        Event::dispatch(new OrderPlaced($order));\n    }\n}\n\n\u002F\u002F Using DI (more testable)\nclass OrderController\n{\n    public function __construct(\n        private Logger $log,\n        private Cache $cache,\n        private Dispatcher $events\n    ) {}\n\n    public function store()\n    {\n        $this->log->info('Processing order');\n        $this->cache->put('last_order', $order->id);\n        $this->events->dispatch(new OrderPlaced($order));\n    }\n}\n```\n\n**Common Facades:**\n\n```php\nuse Illuminate\\Support\\Facades\\Auth;\nAuth::user();\nAuth::check();\nAuth::id();\n\nuse Illuminate\\Support\\Facades\\DB;\nDB::table('users')->get();\nDB::transaction(function () {});\n\nuse Illuminate\\Support\\Facades\\Route;\nRoute::get('\u002Fhome', [HomeController::class, 'index']);\n\nuse Illuminate\\Support\\Facades\\Request;\nRequest::input('name');\nRequest::isMethod('post');\n\nuse Illuminate\\Support\\Facades\\Response;\nResponse::json(['data' => []]);\nResponse::download($file);\n\nuse Illuminate\\Support\\Facades\\Schema;\nSchema::create('table', function ($table) {});\n\nuse Illuminate\\Support\\Facades\\Storage;\nStorage::disk('s3')->put('file.txt', 'content');\n\nuse Illuminate\\Support\\Facades\\Validator;\nValidator::make($data, $rules);\n```\n\n**Pros & Cons:**\n\n| Pros | Cons |\n|------|------|\n| Concise, readable syntax | Hidden dependencies |\n| Easy to mock for testing | Harder to refactor |\n| Great for cross-cutting concerns | Can mask complexity |\n| IDE support with docblocks | Static calls not OOP |\n| No need to inject everywhere | Can encourage bad practices |\n\n**Best Practices:**\n- Use facades for well-known Laravel services\n- Prefer dependency injection for custom classes\n- Create facades only for frequently used services\n- Avoid facades in domain\u002Fbusiness logic\n- Use real-time facades sparingly\n\n**Performance Considerations:**\n- Facade resolution is cached per request\n- Slight overhead vs direct injection\n- Not significant for most applications\n- Use DI in performance-critical code\n\n**Common Mistakes:**\n- Overusing facades in business logic\n- Mocking facades in every test\n- Creating facades for everything\n- Not understanding the underlying container resolution\n\n**Follow-up Questions:**\n- What's the difference between facades and helper functions?\n- How do you test code that uses facades?\n- Can you create facades for your own classes?\n- What are real-time facades and when to use them?",[212,216,217,218],"Static Proxies","Testing","Design Patterns",{"id":220,"category":200,"question":221,"answer":222,"level":173,"tags":223},18,"Compare Dependency Injection vs not using DI with examples.","Dependency Injection is a design pattern that promotes loose coupling and testable code by injecting dependencies rather than creating them internally.\n\n**Without DI (Tight Coupling - Bad):**\n\n```php\nclass OrderController\n{\n    public function store(Request $request)\n    {\n        \u002F\u002F Direct instantiation - tightly coupled\n        $gateway = new StripePaymentGateway(\n            config('services.stripe.key')\n        );\n        $gateway->charge($request->amount);\n\n        $mailer = new SmtpMailer(\n            config('mail.host'),\n            config('mail.port'),\n            config('mail.username'),\n            config('mail.password')\n        );\n        $mailer->send($request->email, 'Order confirmed');\n\n        $logger = new FileLogger(storage_path('logs\u002Forders.log'));\n        $logger->log('Order placed: ' . $request->order_id);\n\n        return response()->json(['success' => true]);\n    }\n}\n\n\u002F\u002F Problems:\n\u002F\u002F 1. Cannot test without real Stripe API\n\u002F\u002F 2. Cannot switch payment providers\n\u002F\u002F 3. Hard to mock dependencies\n\u002F\u002F 4. Violates Single Responsibility Principle\n\u002F\u002F 5. Changes in dependencies require changes in controller\n```\n\n**With DI (Loose Coupling - Good):**\n\n```php\n\u002F\u002F Interfaces for abstraction\ninterface PaymentGatewayInterface\n{\n    public function charge(float $amount, string $currency): array;\n}\n\ninterface MailerInterface\n{\n    public function send(string $email, string $message): void;\n}\n\ninterface LoggerInterface\n{\n    public function log(string $message): void;\n}\n\n\u002F\u002F Concrete implementations\nclass StripeGateway implements PaymentGatewayInterface\n{\n    public function __construct(private string $apiKey) {}\n\n    public function charge(float $amount, string $currency): array\n    {\n        \u002F\u002F Stripe implementation\n    }\n}\n\nclass SmtpMailer implements MailerInterface\n{\n    public function __construct(\n        private string $host,\n        private int $port,\n        private string $username,\n        private string $password\n    ) {}\n\n    public function send(string $email, string $message): void\n    {\n        \u002F\u002F SMTP implementation\n    }\n}\n\nclass FileLogger implements LoggerInterface\n{\n    public function __construct(private string $path) {}\n\n    public function log(string $message): void\n    {\n        file_put_contents($this->path, $message . PHP_EOL, FILE_APPEND);\n    }\n}\n\n\u002F\u002F Controller with DI\nclass OrderController\n{\n    public function __construct(\n        private PaymentGatewayInterface $gateway,\n        private MailerInterface $mailer,\n        private LoggerInterface $logger\n    ) {}\n\n    public function store(Request $request)\n    {\n        $this->gateway->charge($request->amount, 'usd');\n        $this->mailer->send($request->email, 'Order confirmed');\n        $this->logger->log('Order placed: ' . $request->order_id);\n\n        return response()->json(['success' => true]);\n    }\n}\n\n\u002F\u002F Service Provider binding\nclass AppServiceProvider extends ServiceProvider\n{\n    public function register(): void\n    {\n        $this->app->bind(PaymentGatewayInterface::class, function ($app) {\n            return new StripeGateway(config('services.stripe.key'));\n        });\n\n        $this->app->bind(MailerInterface::class, function ($app) {\n            return new SmtpMailer(\n                config('mail.host'),\n                config('mail.port'),\n                config('mail.username'),\n                config('mail.password')\n            );\n        });\n\n        $this->app->bind(LoggerInterface::class, function ($app) {\n            return new FileLogger(storage_path('logs\u002Forders.log'));\n        });\n    }\n}\n```\n\n**Benefits of DI:**\n\n1. **Easy Testing:**\n```php\nclass OrderControllerTest extends TestCase\n{\n    public function test_order_placement()\n    {\n        \u002F\u002F Create mocks\n        $gateway = $this->createMock(PaymentGatewayInterface::class);\n        $gateway->expects($this->once())\n            ->method('charge')\n            ->with(100, 'usd')\n            ->willReturn(['success' => true]);\n\n        $mailer = $this->createMock(MailerInterface::class);\n        $logger = $this->createMock(LoggerInterface::class);\n\n        \u002F\u002F Inject mocks\n        $controller = new OrderController($gateway, $mailer, $logger);\n\n        $request = Request::create('\u002Forders', 'POST', [\n            'amount' => 100,\n            'email' => 'test@example.com',\n            'order_id' => 123\n        ]);\n\n        $response = $controller->store($request);\n        $this->assertEquals(200, $response->getStatusCode());\n    }\n}\n```\n\n2. **Flexible Configuration:**\n```php\n\u002F\u002F Development environment\n$this->app->bind(PaymentGatewayInterface::class, FakePaymentGateway::class);\n\n\u002F\u002F Production environment\n$this->app->bind(PaymentGatewayInterface::class, StripeGateway::class);\n\n\u002F\u002F Contextual binding for different users\n$this->app->when(AdminOrderController::class)\n    ->needs(PaymentGatewayInterface::class)\n    ->give(AdminPaymentGateway::class);\n```\n\n3. **Single Responsibility:**\n```php\n\u002F\u002F Each class has one reason to change\nclass PaymentProcessor\n{\n    \u002F\u002F Handles payment logic only\n}\n\nclass EmailService\n{\n    \u002F\u002F Handles email logic only\n}\n\nclass OrderService\n{\n    \u002F\u002F Coordinates order flow\n}\n```\n\n**Types of Dependency Injection:**\n\n```php\n\u002F\u002F 1. Constructor Injection (Most Common)\nclass UserService\n{\n    public function __construct(\n        private UserRepository $repository,\n        private EventDispatcher $events\n    ) {}\n}\n\n\u002F\u002F 2. Method Injection\nclass ReportController\n{\n    public function generate(Request $request, ReportGenerator $generator)\n    {\n        return $generator->make($request->all());\n    }\n}\n\n\u002F\u002F 3. Property Injection (Not recommended)\nclass Controller\n{\n    public $service;\n\n    public function __construct()\n    {\n        $this->service = app()->make(Service::class); \u002F\u002F Service locator\n    }\n}\n\n\u002F\u002F 4. Setter Injection (Use sparingly)\nclass UserController\n{\n    private $logger;\n\n    public function setLogger(Logger $logger)\n    {\n        $this->logger = $logger;\n    }\n}\n```\n\n**Real-World Example: Service Layer with DI**\n\n```php\n\u002F\u002F Without DI - Hard to test and maintain\nclass CheckoutService\n{\n    public function process(Order $order)\n    {\n        \u002F\u002F Creates dependencies internally\n        $payment = new StripePayment();\n        $inventory = new DatabaseInventory();\n        $email = new SendGridMailer();\n        $log = new FileLogger();\n\n        $payment->charge($order->total);\n        $inventory->deduct($order->items);\n        $email->send($order->user->email, 'Order confirmed');\n        $log->write('Order processed');\n    }\n}\n\n\u002F\u002F With DI - Clean, testable, flexible\nclass CheckoutService\n{\n    public function __construct(\n        private PaymentGateway $payment,\n        private InventoryService $inventory,\n        private Mailer $mailer,\n        private Logger $logger\n    ) {}\n\n    public function process(Order $order): void\n    {\n        $this->payment->charge($order->total);\n        $this->inventory->deduct($order->items);\n        $this->mailer->send($order->user->email, 'Order confirmed');\n        $this->logger->info('Order processed', ['order_id' => $order->id]);\n    }\n}\n```\n\n**When to Use DI vs Not:**\n\n| Use DI | Avoid DI |\n|--------|----------|\n| Custom business logic | Simple value objects |\n| External services (APIs, DB) | Data Transfer Objects (DTOs) |\n| Complex dependencies | Static helper functions |\n| Classes with configurable behavior | Simple utility classes |\n| Code that needs testing | Configuration arrays |\n\n**Common Anti-Patterns:**\n\n```php\n\u002F\u002F Service Locator (Avoid)\nclass BadController\n{\n    public function store()\n    {\n        $service = app()->make(PaymentService::class); \u002F\u002F Hidden dependency\n    }\n}\n\n\u002F\u002F Too many dependencies (Consider splitting)\nclass GodClass\n{\n    public function __construct(\n        private Service1 $s1,\n        private Service2 $s2,\n        \u002F\u002F ... 10+ dependencies\n        private Service15 $s15\n    ) {}\n}\n\n\u002F\u002F Optional dependencies (Use Null Object pattern)\nclass UserController\n{\n    public function __construct(?Logger $logger = null)\n    {\n        $this->logger = $logger ?? new NullLogger();\n    }\n}\n```\n\n**Performance Impact:**\n- Minimal overhead for DI\n- Container caches resolved instances\n- Benefits outweigh small performance cost\n- Use singleton for stateless services\n\n**Security Benefits:**\n- Easy to swap implementations for different security contexts\n- Can inject audit logging automatically\n- Centralized dependency management\n\n**Follow-up Questions:**\n- How does Laravel's container resolve dependencies automatically?\n- What's the difference between DI and Service Locator pattern?\n- When would you use method injection over constructor injection?\n- How do you handle circular dependencies in DI?",[200,224,20,217],"SOLID",{"id":226,"category":227,"question":228,"answer":229,"level":173,"tags":230},19,"Events & Listeners","How do Events and Listeners work in Laravel?","Events provide a simple observer pattern implementation for decoupled communication between different parts of your application.\n\n**Creating Events:**\n\n```bash\nphp artisan make:event OrderPlaced\nphp artisan make:event UserRegistered\n```\n\n```php\nnamespace App\\Events;\n\nuse App\\Models\\Order;\nuse Illuminate\\Broadcasting\\InteractsWithSockets;\nuse Illuminate\\Foundation\\Events\\Dispatchable;\nuse Illuminate\\Queue\\SerializesModels;\n\nclass OrderPlaced\n{\n    use Dispatchable, InteractsWithSockets, SerializesModels;\n\n    \u002F**\n     * Create a new event instance.\n     *\u002F\n    public function __construct(\n        public Order $order,\n        public array $metadata = []\n    ) {}\n\n    \u002F**\n     * Get the channels the event should broadcast on.\n     *\u002F\n    public function broadcastOn(): array\n    {\n        return [new PrivateChannel('orders.' . $this->order->id)];\n    }\n\n    \u002F**\n     * The event's broadcast name.\n     *\u002F\n    public function broadcastAs(): string\n    {\n        return 'order.placed';\n    }\n}\n```\n\n**Creating Listeners:**\n\n```bash\nphp artisan make:listener SendOrderNotification --event=OrderPlaced\nphp artisan make:listener UpdateInventory --event=OrderPlaced\n```\n\n```php\nnamespace App\\Listeners;\n\nuse App\\Events\\OrderPlaced;\nuse App\\Notifications\\OrderConfirmation;\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\nuse Illuminate\\Support\\Facades\\Log;\n\nclass SendOrderNotification implements ShouldQueue\n{\n    \u002F**\n     * The name of the queue the job should be sent to.\n     *\u002F\n    public $queue = 'notifications';\n\n    \u002F**\n     * The number of seconds to wait before processing the job.\n     *\u002F\n    public $delay = 10;\n\n    \u002F**\n     * Handle the event.\n     *\u002F\n    public function handle(OrderPlaced $event): void\n    {\n        $event->order->user->notify(\n            new OrderConfirmation($event->order)\n        );\n\n        Log::info('Order notification sent', [\n            'order_id' => $event->order->id,\n            'user_id' => $event->order->user_id\n        ]);\n    }\n\n    \u002F**\n     * Handle a job failure.\n     *\u002F\n    public function failed(OrderPlaced $event, \\Throwable $e): void\n    {\n        Log::error('Order notification failed', [\n            'order_id' => $event->order->id,\n            'error' => $e->getMessage()\n        ]);\n    }\n}\n```\n\n**Registering Events & Listeners:**\n\n```php\n\u002F\u002F app\u002FProviders\u002FEventServiceProvider.php\nnamespace App\\Providers;\n\nuse Illuminate\\Foundation\\Support\\Providers\\EventServiceProvider as ServiceProvider;\n\nclass EventServiceProvider extends ServiceProvider\n{\n    protected $listen = [\n        \u002F\u002F Standard events\n        OrderPlaced::class => [\n            SendOrderNotification::class,\n            UpdateInventory::class,\n            ProcessPayment::class,\n            NotifyWarehouse::class,\n        ],\n\n        UserRegistered::class => [\n            SendWelcomeEmail::class,\n            CreateUserProfile::class,\n            AssignDefaultRole::class,\n        ],\n\n        \u002F\u002F Wildcard event listeners\n        'eloquent.*' => [\n            LogModelActivity::class,\n        ],\n    ];\n\n    protected $subscribe = [\n        UserEventSubscriber::class,\n        OrderEventSubscriber::class,\n    ];\n\n    \u002F\u002F Event discovery\n    public function shouldDiscoverEvents(): bool\n    {\n        return true;\n    }\n\n    \u002F\u002F Custom event discovery path\n    protected function discoverEventsWithin(): array\n    {\n        return [\n            $this->app->path('Listeners'),\n            $this->app->path('Events'),\n        ];\n    }\n}\n```\n\n**Dispatching Events:**\n\n```php\nuse App\\Events\\OrderPlaced;\n\n\u002F\u002F Method 1: event() helper\nevent(new OrderPlaced($order));\n\n\u002F\u002F Method 2: dispatch method\nOrderPlaced::dispatch($order);\n\n\u002F\u002F Method 3: dispatchIf \u002F dispatchUnless\nOrderPlaced::dispatchIf($condition, $order);\n\n\u002F\u002F Method 4: dispatchNow (sync, no queue)\nOrderPlaced::dispatchNow($order);\n\n\u002F\u002F Method 5: dispatchAfterResponse (after HTTP response)\nOrderPlaced::dispatchAfterResponse($order);\n\n\u002F\u002F With additional data\nOrderPlaced::dispatch($order, ['source' => 'web', 'timestamp' => now()]);\n```\n\n**Event Subscribers:**\n\n```php\nnamespace App\\Listeners;\n\nuse Illuminate\\Events\\Dispatcher;\n\nclass UserEventSubscriber\n{\n    \u002F**\n     * Handle user login events.\n     *\u002F\n    public function handleUserLogin($event): void\n    {\n        Log::info('User logged in', ['user_id' => $event->user->id]);\n    }\n\n    \u002F**\n     * Handle user logout events.\n     *\u002F\n    public function handleUserLogout($event): void\n    {\n        Log::info('User logged out', ['user_id' => $event->user->id]);\n    }\n\n    \u002F**\n     * Register the listeners for the subscriber.\n     *\u002F\n    public function subscribe(Dispatcher $events): void\n    {\n        $events->listen(\n            'Illuminate\\Auth\\Events\\Login',\n            [UserEventSubscriber::class, 'handleUserLogin']\n        );\n\n        $events->listen(\n            'Illuminate\\Auth\\Events\\Logout',\n            [UserEventSubscriber::class, 'handleUserLogout']\n        );\n    }\n}\n```\n\n**Queued Listeners:**\n\n```php\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\nuse Illuminate\\Queue\\InteractsWithQueue;\n\nclass ProcessPayment implements ShouldQueue\n{\n    use InteractsWithQueue;\n\n    \u002F\u002F Custom connection\n    public $connection = 'redis';\n\n    \u002F\u002F Custom queue\n    public $queue = 'payments';\n\n    \u002F\u002F Max attempts\n    public $tries = 3;\n\n    \u002F\u002F Timeout\n    public $timeout = 60;\n\n    \u002F\u002F Rate limiting\n    public $middleware = [\n        new RateLimited,\n    ];\n\n    public function handle(OrderPlaced $event): void\n    {\n        \u002F\u002F Process payment\n        if ($this->attempts() > 2) {\n            $this->release(30); \u002F\u002F Release back to queue\n        }\n    }\n\n    \u002F\u002F Determine if the listener should be queued\n    public function shouldQueue(OrderPlaced $event): bool\n    {\n        return $event->order->total > 0;\n    }\n}\n```\n\n**Model Events:**\n\n```php\n\u002F\u002F In Model\nclass User extends Model\n{\n    \u002F\u002F Boot method\n    protected static function booted(): void\n    {\n        static::created(function ($user) {\n            Log::info('User created: ' . $user->id);\n        });\n\n        static::updated(function ($user) {\n            Log::info('User updated: ' . $user->id);\n        });\n\n        static::deleted(function ($user) {\n            Log::info('User deleted: ' . $user->id);\n        });\n    }\n}\n\n\u002F\u002F Available model events\n\u002F\u002F retrieved, creating, created, updating, updated, saving, saved,\n\u002F\u002F deleting, deleted, restoring, restored, replicating\n```\n\n**Broadcasting Events:**\n\n```php\n\u002F\u002F Event for real-time broadcasting\nclass OrderStatusUpdated implements ShouldBroadcast\n{\n    use Dispatchable, InteractsWithSockets, SerializesModels;\n\n    public function __construct(\n        public Order $order,\n        public string $status\n    ) {}\n\n    public function broadcastOn(): array\n    {\n        return [\n            new PrivateChannel('orders.' . $this->order->id),\n            new PresenceChannel('order-updates')\n        ];\n    }\n\n    public function broadcastWith(): array\n    {\n        return [\n            'id' => $this->order->id,\n            'status' => $this->status,\n            'updated_at' => now()->toIso8601String()\n        ];\n    }\n}\n\n\u002F\u002F Client-side (Laravel Echo)\nEcho.private(`orders.${orderId}`)\n    .listen('OrderStatusUpdated', (e) => {\n        console.log(e.status);\n    });\n```\n\n**Testing Events:**\n\n```php\nuse Illuminate\\Support\\Facades\\Event;\n\npublic function test_order_placed_event_dispatched()\n{\n    Event::fake();\n\n    \u002F\u002F Perform order placement\n    $this->post('\u002Forders', [...])->assertStatus(200);\n\n    \u002F\u002F Assert event was dispatched\n    Event::assertDispatched(OrderPlaced::class, function ($event) {\n        return $event->order->total === 100;\n    });\n\n    \u002F\u002F Assert listener was called\n    Event::assertListening(\n        OrderPlaced::class,\n        SendOrderNotification::class\n    );\n\n    \u002F\u002F Assert event not dispatched\n    Event::assertNotDispatched(OrderFailed::class);\n}\n```\n\n**Best Practices:**\n- Use events for cross-cutting concerns (logging, notifications)\n- Keep event classes small and focused\n- Use queued listeners for time-consuming operations\n- Don't overuse events (can make flow hard to follow)\n- Document event payload structure\n- Use type hints for event properties\n\n**Performance Considerations:**\n- Queue heavy listeners to avoid slowing responses\n- Use batch processing for many events\n- Monitor queue size and failed jobs\n- Consider event discovery performance in large apps\n\n**Common Mistakes:**\n- Putting too much logic in events\n- Forgetting to register listeners\n- Dispatching events inside loops\n- Not handling failed queued listeners\n- Using sync listeners for slow operations\n\n**Security Considerations:**\n- Validate event data before dispatching\n- Don't expose sensitive data in broadcast events\n- Implement authorization for private channels\n- Sanitize data passed to events\n\n**Follow-up Questions:**\n- How do you handle event dependencies?\n- What's the difference between events and jobs?\n- How do you test queued event listeners?\n- When should you use model events vs custom events?",[231,232,233,234],"Events","Listeners","Observer Pattern","Queues",{"id":236,"category":237,"question":238,"answer":239,"level":173,"tags":240},20,"Queues & Jobs","How do you implement queues and jobs in Laravel?","Queues allow you to defer time-consuming tasks, improving application response times.\n\n**Configuration:**\n\n```php\n\u002F\u002F config\u002Fqueue.php\n'default' => env('QUEUE_CONNECTION', 'redis'),\n\n'connections' => [\n    'sync' => [\n        'driver' => 'sync', \u002F\u002F No queue, runs immediately\n    ],\n    'database' => [\n        'driver' => 'database',\n        'table' => 'jobs',\n        'queue' => 'default',\n        'retry_after' => 90,\n    ],\n    'redis' => [\n        'driver' => 'redis',\n        'connection' => 'default',\n        'queue' => env('REDIS_QUEUE', 'default'),\n        'retry_after' => 90,\n        'block_for' => null,\n    ],\n    'sqs' => [\n        'driver' => 'sqs',\n        'key' => env('AWS_ACCESS_KEY_ID'),\n        'secret' => env('AWS_SECRET_ACCESS_KEY'),\n        'prefix' => env('SQS_PREFIX'),\n        'queue' => env('SQS_QUEUE'),\n        'suffix' => env('SQS_SUFFIX'),\n    ],\n],\n\n'failed' => [\n    'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),\n    'database' => env('DB_CONNECTION', 'mysql'),\n    'table' => 'failed_jobs',\n],\n```\n\n**Creating Jobs:**\n\n```bash\nphp artisan make:job ProcessPodcast\nphp artisan make:job SendWelcomeEmail\n```\n\n```php\nnamespace App\\Jobs;\n\nuse App\\Models\\Podcast;\nuse App\\Services\\AudioProcessor;\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\nuse Illuminate\\Foundation\\Bus\\Dispatchable;\nuse Illuminate\\Queue\\InteractsWithQueue;\nuse Illuminate\\Queue\\SerializesModels;\nuse Illuminate\\Support\\Facades\\Log;\n\nclass ProcessPodcast implements ShouldQueue\n{\n    use Dispatchable, InteractsWithQueue, SerializesModels;\n\n    \u002F\u002F Max attempts\n    public $tries = 3;\n\n    \u002F\u002F Timeout in seconds\n    public $timeout = 120;\n\n    \u002F\u002F Max exceptions before failing\n    public $maxExceptions = 2;\n\n    \u002F\u002F Queue name\n    public $queue = 'media';\n\n    \u002F\u002F Connection\n    public $connection = 'redis';\n\n    \u002F\u002F Delay\n    public $delay = 10; \u002F\u002F seconds\n\n    \u002F\u002F Unique job\n    public $uniqueFor = 3600; \u002F\u002F seconds\n\n    \u002F**\n     * Create a new job instance.\n     *\u002F\n    public function __construct(\n        public Podcast $podcast,\n        public array $options = []\n    ) {}\n\n    \u002F**\n     * Execute the job.\n     *\u002F\n    public function handle(AudioProcessor $processor): void\n    {\n        \u002F\u002F Process the podcast\n        $processor->process($this->podcast);\n\n        \u002F\u002F Update status\n        $this->podcast->update(['processed_at' => now()]);\n\n        \u002F\u002F Dispatch another job\n        GenerateTranscript::dispatch($this->podcast);\n    }\n\n    \u002F**\n     * Get the unique ID for the job.\n     *\u002F\n    public function uniqueId(): string\n    {\n        return $this->podcast->id;\n    }\n\n    \u002F**\n     * Determine if the job should be unique.\n     *\u002F\n    public function uniqueFor(): int\n    {\n        return 3600;\n    }\n\n    \u002F**\n     * Handle a job failure.\n     *\u002F\n    public function failed(\\Throwable $e): void\n    {\n        Log::error('Podcast processing failed', [\n            'podcast_id' => $this->podcast->id,\n            'error' => $e->getMessage()\n        ]);\n\n        \u002F\u002F Notify admin\n        NotifyAdmin::dispatch($this->podcast, $e);\n    }\n\n    \u002F**\n     * Get the middleware the job should pass through.\n     *\u002F\n    public function middleware(): array\n    {\n        return [\n            new RateLimitedMiddleware,\n            new PreventDuplicateMiddleware,\n        ];\n    }\n\n    \u002F**\n     * Determine the time at which the job should timeout.\n     *\u002F\n    public function retryUntil(): \\DateTime\n    {\n        return now()->addMinutes(10);\n    }\n}\n```\n\n**Dispatching Jobs:**\n\n```php\nuse App\\Jobs\\ProcessPodcast;\n\n\u002F\u002F Basic dispatch\nProcessPodcast::dispatch($podcast);\n\n\u002F\u002F Dispatch with delay\nProcessPodcast::dispatch($podcast)->delay(now()->addMinutes(10));\n\n\u002F\u002F Dispatch after response\nProcessPodcast::dispatchAfterResponse($podcast);\n\n\u002F\u002F Dispatch to specific queue\nProcessPodcast::dispatch($podcast)->onQueue('high-priority');\n\n\u002F\u002F Dispatch to specific connection\nProcessPodcast::dispatch($podcast)->onConnection('sqs');\n\n\u002F\u002F Dispatch with chain\nProcessPodcast::withChain([\n    new GenerateTranscript($podcast),\n    new SendNotification($podcast)\n])->dispatch($podcast);\n\n\u002F\u002F Dispatch if condition\nProcessPodcast::dispatchIf($podcast->needsProcessing(), $podcast);\n\n\u002F\u002F Dispatch unless condition\nProcessPodcast::dispatchUnless($podcast->isProcessed(), $podcast);\n\n\u002F\u002F Batch dispatch\n$batch = Bus::batch([\n    new ProcessPodcast($podcast1),\n    new ProcessPodcast($podcast2),\n    new ProcessPodcast($podcast3),\n])->then(function (Batch $batch) {\n    \u002F\u002F All jobs completed\n})->catch(function (Batch $batch, Throwable $e) {\n    \u002F\u002F First batch job failure detected\n})->finally(function (Batch $batch) {\n    \u002F\u002F Batch has finished executing\n})->dispatch();\n\n\u002F\u002F Chain multiple jobs\nBus::chain([\n    new ProcessPodcast($podcast),\n    new GenerateTranscript($podcast),\n    new SendNotification($podcast),\n])->dispatch();\n```\n\n**Running Queue Workers:**\n\n```bash\n# Basic worker\nphp artisan queue:work\n\n# Specific connection\nphp artisan queue:work redis\n\n# Specific queue\nphp artisan queue:work --queue=high,default\n\n# Run once (single job)\nphp artisan queue:work --once\n\n# Stop when empty\nphp artisan queue:work --stop-when-empty\n\n# Sleep duration between checks\nphp artisan queue:work --sleep=3\n\n# Memory limit\nphp artisan queue:work --memory=512\n\n# Timeout\nphp artisan queue:work --timeout=60\n\n# Max attempts\nphp artisan queue:work --tries=3\n\n# Daemon worker (no restart)\nphp artisan queue:work --daemon\n\n# Listen (for local development)\nphp artisan queue:listen\n```\n\n**Job Middleware:**\n\n```php\nnamespace App\\Jobs\\Middleware;\n\nuse Illuminate\\Support\\Facades\\Redis;\n\nclass RateLimitedMiddleware\n{\n    public function handle($job, $next)\n    {\n        Redis::throttle('key')\n            ->allow(10)\n            ->every(60)\n            ->then(function () use ($job, $next) {\n                $next($job);\n            }, function () use ($job) {\n                $job->release(10);\n            });\n    }\n}\n```\n\n**Failed Jobs:**\n\n```bash\n# List failed jobs\nphp artisan queue:failed\n\n# Retry specific job\nphp artisan queue:retry 1\n\n# Retry all failed jobs\nphp artisan queue:retry all\n\n# Delete failed job\nphp artisan queue:forget 1\n\n# Delete all failed jobs\nphp artisan queue:flush\n```\n\n```php\n\u002F\u002F app\u002FExceptions\u002FHandler.php\npublic function register(): void\n{\n    $this->reportable(function (JobFailedException $e) {\n        \u002F\u002F Custom failed job handling\n    });\n}\n\n\u002F\u002F app\u002FProviders\u002FAppServiceProvider.php\npublic function boot(): void\n{\n    Queue::failing(function (JobFailed $event) {\n        Log::error('Job failed', [\n            'job' => $event->job->resolveName(),\n            'exception' => $event->exception->getMessage()\n        ]);\n    });\n}\n```\n\n**Job Batching:**\n\n```php\n\u002F\u002F Create batch\n$batch = Bus::batch([\n    new ProcessPodcast($podcast1),\n    new ProcessPodcast($podcast2),\n])->then(function (Batch $batch) {\n    \u002F\u002F All jobs completed\n})->catch(function (Batch $batch, Throwable $e) {\n    \u002F\u002F First batch job failure detected\n})->finally(function (Batch $batch) {\n    \u002F\u002F Batch finished\n})->dispatch();\n\n\u002F\u002F Track batch\n$batchId = $batch->id;\n$batch = Bus::findBatch($batchId);\n\n\u002F\u002F Add to batch\n$batch->add(new ProcessPodcast($podcast3));\n\n\u002F\u002F Cancel batch\n$batch->cancel();\n\n\u002F\u002F Batch progress\n$progress = $batch->progress(); \u002F\u002F 0-100\n$completed = $batch->completedJobs;\n$pending = $batch->pendingJobs;\n$failed = $batch->failedJobs;\n```\n\n**Rate Limiting:**\n\n```php\n\u002F\u002F In AppServiceProvider\nuse Illuminate\\Cache\\RateLimiting\\Limit;\nuse Illuminate\\Support\\Facades\\RateLimiter;\n\nRateLimiter::for('processing', function ($job) {\n    return Limit::perMinute(100)->by($job->podcast->user_id);\n});\n\n\u002F\u002F In job\npublic function middleware(): array\n{\n    return [\n        new RateLimited('processing')\n    ];\n}\n```\n\n**Testing Jobs:**\n\n```php\nuse Illuminate\\Support\\Facades\\Queue;\n\npublic function test_job_is_dispatched()\n{\n    Queue::fake();\n\n    $this->post('\u002Fpodcasts', [...]);\n\n    Queue::assertPushed(ProcessPodcast::class, function ($job) {\n        return $job->podcast->id === 1;\n    });\n\n    Queue::assertPushedOn('media', ProcessPodcast::class);\n    Queue::assertNotPushed(SendEmail::class);\n}\n```\n\n**Supervisor Configuration:**\n\n```ini\n[program:laravel-worker]\nprocess_name=%(program_name)s_%(process_num)02d\ncommand=php \u002Fvar\u002Fwww\u002Fartisan queue:work redis --sleep=3 --tries=3 --max-time=3600\nautostart=true\nautorestart=true\nstopasgroup=true\nkillasgroup=true\nuser=forge\nnumprocs=8\nredirect_stderr=true\nstdout_logfile=\u002Fvar\u002Fwww\u002Fstorage\u002Flogs\u002Fworker.log\nstopwaitsecs=3600\n```\n\n**Best Practices:**\n- Keep jobs small and focused\n- Make jobs idempotent (can run multiple times)\n- Use unique jobs to prevent duplicates\n- Set appropriate timeouts and retry limits\n- Monitor queue size and failed jobs\n- Use supervisor for production\n- Implement proper logging\n\n**Performance Tips:**\n- Use Redis for better performance\n- Increase worker count for high volume\n- Use separate queues for different priorities\n- Batch similar operations\n- Use database indexing for jobs table\n\n**Common Mistakes:**\n- Jobs not being idempotent\n- Missing ShouldQueue interface\n- Not handling failed jobs\n- Memory leaks in long-running workers\n- Too many jobs on single queue\n\n**Security Considerations:**\n- Validate job data before processing\n- Don't serialize sensitive data\n- Use encryption for sensitive job data\n- Implement rate limiting\n\n**Follow-up Questions:**\n- How do you handle job dependencies?\n- What's the difference between queue:work and queue:listen?\n- How do you monitor queue health?\n- When should you use batches vs chains?",[234,241,242,243],"Jobs","Background Processing","Performance",{"id":245,"category":246,"question":247,"answer":248,"level":173,"tags":249},36,"Intermediate","What are Laravel Gates and Policies for authorization?","Gates and Policies provide a structured way to authorize user actions. Gates are closures, Policies are classes organized by model.\n\n**Gates (Simple Authorization):**\n\n```php\n\u002F\u002F AppServiceProvider\nuse Illuminate\\Support\\Facades\\Gate;\n\npublic function boot()\n{\n    \u002F\u002F Simple gate\n    Gate::define('edit-settings', function ($user) {\n        return $user->is_admin;\n    });\n    \n    \u002F\u002F With model\n    Gate::define('update-post', function ($user, $post) {\n        return $user->id === $post->user_id || $user->is_admin;\n    });\n    \n    \u002F\u002F Using class\n    Gate::define('delete-post', [PostPolicy::class, 'delete']);\n}\n\n\u002F\u002F Using gates\nif (Gate::allows('edit-settings')) { }\nif (Gate::denies('update-post', $post)) { }\nGate::authorize('delete-post', $post);\n\n\u002F\u002F For users\nif ($request->user()->can('update-post', $post)) { }\n```\n\n**Policies (Model-Based Authorization):**\n\n```bash\nphp artisan make:policy PostPolicy --model=Post\n```\n\n```php\n\u002F\u002F app\u002FPolicies\u002FPostPolicy.php\nclass PostPolicy\n{\n    public function view(User $user, Post $post): bool\n    {\n        return $user->id === $post->user_id || !$post->is_private;\n    }\n    \n    public function create(User $user): bool\n    {\n        return $user->is_verified;\n    }\n    \n    public function update(User $user, Post $post): bool\n    {\n        return $user->id === $post->user_id;\n    }\n    \n    public function delete(User $user, Post $post): bool\n    {\n        return $user->id === $post->user_id || $user->is_admin;\n    }\n    \n    public function before(User $user, $ability): ?bool\n    {\n        if ($user->is_super_admin) {\n            return true; \u002F\u002F Override all permissions\n        }\n        return null;\n    }\n}\n\n\u002F\u002F Register policy (AuthServiceProvider)\nprotected $policies = [\n    Post::class => PostPolicy::class,\n];\n```\n\n**Using Policies:**\n\n```php\n\u002F\u002F In controller\npublic function update(Request $request, Post $post)\n{\n    $this->authorize('update', $post);\n    \u002F\u002F Or\n    if ($request->user()->cannot('update', $post)) {\n        abort(403);\n    }\n}\n\n\u002F\u002F In blade\n@can('update', $post)\n    \u003Ca href=\"\u002Fposts\u002F{{ $post->id }}\u002Fedit\">Edit\u003C\u002Fa>\n@endcan\n\n@cannot('delete', $post)\n    \u003Cp>You cannot delete this post\u003C\u002Fp>\n@endcannot\n\n\u002F\u002F Via middleware\nRoute::put('\u002Fposts\u002F{post}', function (Post $post) {\n    \u002F\u002F\n})->middleware('can:update,post');\n```\n\n**Guest Users:**\n\n```php\n\u002F\u002F Allow guests\nGate::define('view-document', function ($user = null, $document) {\n    return $document->is_public;\n});\n\n\u002F\u002F In policy (optional user)\npublic function view(?User $user, Post $post): bool\n{\n    return $post->is_public || ($user && $user->id === $post->user_id);\n}\n```\n\n**Best Practices:**\n- Use Policies for model-specific authorization\n- Use Gates for general application rules\n- Keep authorization logic in one place\n- Use `before` method sparingly\n- Test policies with user roles\n\n**Performance:** Gates and Policies are resolved from the container and cached per request.\n\n**Follow-up Questions:**\n- How do you authorize based on multiple conditions?\n- Can you use Gates with API routes?\n- How do you test authorization logic?",[250,251,252,80],"Authorization","Gates","Policies",{"id":254,"category":246,"question":255,"answer":256,"level":173,"tags":257},37,"How do you implement role-based permissions in Laravel?","Role-based permissions can be implemented using gates, policies, or dedicated packages like Spatie Permission.\n\n**Custom Implementation:**\n\n```php\n\u002F\u002F User model\nclass User extends Authenticatable\n{\n    public function roles()\n    {\n        return $this->belongsToMany(Role::class);\n    }\n    \n    public function hasRole($role): bool\n    {\n        return $this->roles->contains('slug', $role);\n    }\n    \n    public function hasPermission($permission): bool\n    {\n        return $this->roles->flatMap->permissions->contains('slug', $permission);\n    }\n}\n\n\u002F\u002F Role model\nclass Role extends Model\n{\n    public function permissions()\n    {\n        return $this->belongsToMany(Permission::class);\n    }\n}\n\n\u002F\u002F Gates\nGate::define('edit-articles', function ($user) {\n    return $user->hasPermission('edit-articles');\n});\n\n\u002F\u002F Policy\nclass ArticlePolicy\n{\n    public function update(User $user, Article $article)\n    {\n        return $user->hasPermission('edit-articles') || $user->id === $article->user_id;\n    }\n}\n```\n\n**Using Spatie Permission Package:**\n\n```bash\ncomposer require spatie\u002Flaravel-permission\nphp artisan vendor:publish --provider=\"Spatie\\Permission\\PermissionServiceProvider\"\nphp artisan migrate\n```\n\n```php\n\u002F\u002F User model\nuse Spatie\\Permission\\Traits\\HasRoles;\n\nclass User extends Authenticatable\n{\n    use HasRoles;\n}\n\n\u002F\u002F Create permissions and roles\nuse Spatie\\Permission\\Models\\Role;\nuse Spatie\\Permission\\Models\\Permission;\n\n$permission = Permission::create(['name' => 'edit articles']);\n$role = Role::create(['name' => 'writer']);\n$role->givePermissionTo('edit articles');\n$user->assignRole('writer');\n\n\u002F\u002F Check permissions\nif ($user->hasPermissionTo('edit articles')) { }\nif ($user->hasRole('writer')) { }\nif ($user->can('edit articles')) { }\n\n\u002F\u002F Blade directives\n@role('writer')\n    \u003Cp>Writer content\u003C\u002Fp>\n@endrole\n\n@hasrole('admin')\n    \u003Cp>Admin content\u003C\u002Fp>\n@endhasrole\n\n@can('edit articles')\n    \u003Cbutton>Edit\u003C\u002Fbutton>\n@endcan\n```\n\n**Middleware for Roles:**\n\n```php\n\u002F\u002F app\u002FHttp\u002FMiddleware\u002FCheckRole.php\npublic function handle($request, Closure $next, $role)\n{\n    if (!$request->user() || !$request->user()->hasRole($role)) {\n        abort(403);\n    }\n    return $next($request);\n}\n\n\u002F\u002F Register in kernel\nprotected $routeMiddleware = [\n    'role' => \\App\\Http\\Middleware\\CheckRole::class,\n];\n\n\u002F\u002F Usage\nRoute::get('\u002Fadmin', [AdminController::class, 'index'])->middleware('role:admin');\n```\n\n**Best Practices:**\n- Seed default roles and permissions\n- Cache permissions after changes\n- Use middleware for route protection\n- Implement permission sync on role change\n\n**Performance:** Cache permissions to avoid repeated database queries.\n\n**Follow-up Questions:**\n- How do you handle dynamic permissions (e.g., ownership)?\n- How do you migrate existing users to roles?\n- Can you assign multiple roles to a user?",[250,258,259,260],"Roles","Permissions","Spatie",{"id":262,"category":246,"question":263,"answer":264,"level":173,"tags":265},38,"What is the difference between `bind()` and `singleton()` in the service container?","`bind()` creates a new instance each time it's resolved, while `singleton()` returns the same instance throughout the application lifecycle.\n\n**bind() - New Instance Each Time:**\n\n```php\n$this->app->bind(Calculator::class, function ($app) {\n    return new Calculator();\n});\n\n$calc1 = app(Calculator::class);\n$calc2 = app(Calculator::class);\n\u002F\u002F $calc1 !== $calc2 - Different instances\n```\n\n**singleton() - Shared Instance:**\n\n```php\n$this->app->singleton(Config::class, function ($app) {\n    return new Config($app['config']);\n});\n\n$config1 = app(Config::class);\n$config2 = app(Config::class);\n\u002F\u002F $config1 === $config2 - Same instance\n```\n\n**When to Use Each:**\n\n| Use singleton() | Use bind() |\n|-----------------|------------|\n| Stateless services | Stateful services |\n| Configuration classes | Request-specific data |\n| Database connections | Form request instances |\n| Loggers | Controllers |\n| Cache drivers | Job instances |\n\n**Example: Stateful Service (Use bind):**\n\n```php\nclass UserSession\n{\n    private $data = [];\n    \n    public function set($key, $value) { $this->data[$key] = $value; }\n    public function get($key) { return $this->data[$key] ?? null; }\n}\n\n\u002F\u002F Must use bind() - each user needs their own session\n$this->app->bind(UserSession::class);\n```\n\n**Example: Stateless Service (Use singleton):**\n\n```php\nclass PaymentGateway\n{\n    public function __construct(private string $apiKey) {}\n    \n    public function charge($amount) { \u002F* No state stored *\u002F }\n}\n\n\u002F\u002F Can use singleton - safe to share\n$this->app->singleton(PaymentGateway::class, function ($app) {\n    return new PaymentGateway(config('payment.api_key'));\n});\n```\n\n**Lazy Loading with singleton():**\n\n```php\n\u002F\u002F Service isn't instantiated until first resolution\n$this->app->singleton(HeavyService::class, function ($app) {\n    return new HeavyService(); \u002F\u002F Expensive initialization\n});\n```\n\n**Testing Implications:**\n\n```php\n\u002F\u002F bind() creates fresh instances - good for test isolation\n\u002F\u002F singleton() retains state between tests - may cause issues\n\npublic function test_singleton_persists()\n{\n    $instance1 = app(Config::class);\n    $instance2 = app(Config::class);\n    $this->assertSame($instance1, $instance2);\n}\n```\n\n**Performance:** singleton() is slightly faster after first resolution since instance is cached.\n\n**Follow-up Questions:**\n- How do you reset a singleton in tests?\n- Can you convert bind to singleton later?\n- What happens with circular dependencies in singleton?",[195,201,266],"Singleton",{"id":268,"category":246,"question":269,"answer":270,"level":173,"tags":271},39,"What are contextual bindings in Laravel's service container?","Contextual binding allows you to define different implementations of a dependency for different classes.\n\n**Basic Contextual Binding:**\n\n```php\nuse Illuminate\\Support\\Facades\\Storage;\n\n$this->app->when(PhotoController::class)\n    ->needs(Filesystem::class)\n    ->give(function () {\n        return Storage::disk('photos');\n    });\n\n$this->app->when(VideoController::class)\n    ->needs(Filesystem::class)\n    ->give(function () {\n        return Storage::disk('videos');\n    });\n```\n\n**Primitive Values:**\n\n```php\n$this->app->when(ReportGenerator::class)\n    ->needs('$format')\n    ->give('pdf');\n\n$this->app->when(ExportService::class)\n    ->needs('$timeout')\n    ->give(300);\n```\n\n**Interface to Implementation:**\n\n```php\n$this->app->when(OrderController::class)\n    ->needs(PaymentGateway::class)\n    ->give(StripeGateway::class);\n\n$this->app->when(SubscriptionController::class)\n    ->needs(PaymentGateway::class)\n    ->give(PaypalGateway::class);\n```\n\n**Multiple Dependencies:**\n\n```php\n$this->app->when(EmailNotifier::class)\n    ->needs(Mailer::class)\n    ->give(function () {\n        return new SmtpMailer(config('mail'));\n    })\n    ->needs('$retryAttempts')\n    ->give(3);\n```\n\n**Real-World Example:**\n\n```php\n\u002F\u002F Different cache drivers for different services\n$this->app->when(UserService::class)\n    ->needs(Cache::class)\n    ->give(function () {\n        return Cache::store('redis');\n    });\n\n$this->app->when(ReportService::class)\n    ->needs(Cache::class)\n    ->give(function () {\n        return Cache::store('file'); \u002F\u002F Reports don't need fast cache\n    });\n\n\u002F\u002F Different API clients\n$this->app->when(AnalyticsController::class)\n    ->needs(ApiClient::class)\n    ->give(GoogleAnalyticsClient::class);\n\n$this->app->when(AdvertisingController::class)\n    ->needs(ApiClient::class)\n    ->give(FacebookAdsClient::class);\n```\n\n**Testing Contextual Bindings:**\n\n```php\npublic function test_contextual_binding()\n{\n    $this->app->when(TestController::class)\n        ->needs(Logger::class)\n        ->give(MockLogger::class);\n    \n    $controller = $this->app->make(TestController::class);\n    \u002F\u002F $controller gets MockLogger\n}\n```\n\n**Best Practices:**\n- Use for specific edge cases, not as default\n- Keep contextual bindings in service providers\n- Document why different implementations are needed\n- Use with interfaces for flexibility\n\n**Follow-up Questions:**\n- Can contextual binding work with method injection?\n- How do you override contextual bindings in tests?\n- What's the performance impact of contextual binding?",[195,272,200],"Contextual Binding",{"id":274,"category":246,"question":275,"answer":276,"level":173,"tags":277},40,"How do you handle database migrations with foreign key constraints?","Foreign key constraints maintain referential integrity but require careful migration ordering.\n\n**Basic Foreign Keys:**\n\n```php\nSchema::create('posts', function (Blueprint $table) {\n    $table->id();\n    $table->foreignId('user_id')->constrained();\n    $table->string('title');\n    $table->timestamps();\n});\n\n\u002F\u002F Equivalent to:\n$table->unsignedBigInteger('user_id');\n$table->foreign('user_id')->references('id')->on('users');\n```\n\n**Custom Foreign Keys:**\n\n```php\n\u002F\u002F Different column names\n$table->foreignId('author_id')->constrained('users');\n\n\u002F\u002F Custom foreign key name\n$table->foreign('user_id', 'fk_posts_user_id')\n    ->references('id')\n    ->on('users')\n    ->onDelete('cascade');\n\n\u002F\u002F Multiple constraints\n$table->foreignId('category_id')->constrained();\n$table->foreignId('user_id')->constrained()->onDelete('cascade');\n```\n\n**On Delete Actions:**\n\n```php\n\u002F\u002F Cascade - Delete child records\n$table->foreignId('user_id')->constrained()->onDelete('cascade');\n\n\u002F\u002F Set Null - Set foreign key to NULL\n$table->foreignId('user_id')->nullable()->constrained()->onDelete('set null');\n\n\u002F\u002F Restrict - Prevent deletion\n$table->foreignId('user_id')->constrained()->onDelete('restrict');\n\n\u002F\u002F No Action - Same as restrict in some DBs\n$table->foreignId('user_id')->constrained()->onDelete('no action');\n```\n\n**Migration Ordering:**\n\n```php\n\u002F\u002F 2024_01_01_000001_create_users_table.php\nSchema::create('users', function (Blueprint $table) {\n    $table->id();\n    $table->string('name');\n    $table->timestamps();\n});\n\n\u002F\u002F 2024_01_01_000002_create_posts_table.php (depends on users)\nSchema::create('posts', function (Blueprint $table) {\n    $table->id();\n    $table->foreignId('user_id')->constrained();\n    $table->string('title');\n    $table->timestamps();\n});\n```\n\n**Handling Circular Dependencies:**\n\n```php\n\u002F\u002F Temporarily disable foreign key checks\nSchema::disableForeignKeyConstraints();\n\nSchema::create('users', function (Blueprint $table) {\n    $table->id();\n    $table->foreignId('parent_id')->nullable();\n    \u002F\u002F Can't add foreign key yet\n});\n\nSchema::table('users', function (Blueprint $table) {\n    $table->foreign('parent_id')->references('id')->on('users');\n});\n\nSchema::enableForeignKeyConstraints();\n```\n\n**Dropping Foreign Keys:**\n\n```php\n\u002F\u002F Drop by constraint name\nSchema::table('posts', function (Blueprint $table) {\n    $table->dropForeign(['user_id']);\n});\n\n\u002F\u002F Drop by custom name\n$table->dropForeign('fk_posts_user_id');\n\n\u002F\u002F Drop all foreign keys (MySQL)\n$table->dropForeign('posts_user_id_foreign'); \u002F\u002F Laravel's naming: table_column_foreign\n```\n\n**Refreshing Migrations:**\n\n```bash\n# Reset and re-run (order matters)\nphp artisan migrate:refresh\n\n# Fresh (drops all tables)\nphp artisan migrate:fresh\n\n# Specific migration\nphp artisan migrate:refresh --path=\u002Fdatabase\u002Fmigrations\u002F2024_01_01_000002_create_posts_table.php\n```\n\n**Common Issues:**\n\n```php\n\u002F\u002F Error: Cannot add foreign key constraint\n\u002F\u002F Solution: Ensure parent table exists and column types match\n\n\u002F\u002F Error: Cannot drop table because foreign key exists\n\u002F\u002F Solution: Drop child tables first or disable checks\n\n\u002F\u002F Error: Column type mismatch\n\u002F\u002F Solution: Ensure both columns are same type (both bigInteger, both integer, etc.)\n```\n\n**Best Practices:**\n- Name foreign keys consistently\n- Order migrations by dependency\n- Use `constrained()` for brevity\n- Consider `onDelete` behavior carefully\n- Test rollbacks before production\n\n**Performance:** Foreign keys add overhead to INSERT\u002FUPDATE\u002FDELETE operations but ensure data integrity.\n\n**Follow-up Questions:**\n- How do you add foreign keys to existing tables with data?\n- What's the difference between RESTRICT and NO ACTION?\n- How do you handle foreign keys with soft deletes?",[50,278,54,55],"Foreign Keys",{"id":280,"category":246,"question":281,"answer":282,"level":173,"tags":283},41,"What are polymorphic relationships in Eloquent?","Polymorphic relationships allow a model to belong to multiple other models on a single association.\n\n**One-to-Many Polymorphic:**\n\n```php\n\u002F\u002F Post and Video models can have many comments\nclass Comment extends Model\n{\n    public function commentable()\n    {\n        return $this->morphTo();\n    }\n}\n\nclass Post extends Model\n{\n    public function comments()\n    {\n        return $this->morphMany(Comment::class, 'commentable');\n    }\n}\n\nclass Video extends Model\n{\n    public function comments()\n    {\n        return $this->morphMany(Comment::class, 'commentable');\n    }\n}\n\n\u002F\u002F Migration\nSchema::create('comments', function (Blueprint $table) {\n    $table->id();\n    $table->text('content');\n    $table->morphs('commentable'); \u002F\u002F commentable_id + commentable_type\n    $table->timestamps();\n});\n\n\u002F\u002F Usage\n$post = Post::find(1);\n$comment = $post->comments()->create(['content' => 'Great post!']);\n\n$video = Video::find(1);\n$comment = $video->comments()->create(['content' => 'Awesome video!']);\n\n$comment = Comment::find(1);\n$parent = $comment->commentable; \u002F\u002F Returns Post or Video instance\n```\n\n**Many-to-Many Polymorphic:**\n\n```php\n\u002F\u002F Tags can belong to posts and videos\nclass Tag extends Model\n{\n    public function posts()\n    {\n        return $this->morphedByMany(Post::class, 'taggable');\n    }\n    \n    public function videos()\n    {\n        return $this->morphedByMany(Video::class, 'taggable');\n    }\n}\n\nclass Post extends Model\n{\n    public function tags()\n    {\n        return $this->morphToMany(Tag::class, 'taggable');\n    }\n}\n\n\u002F\u002F Migration\nSchema::create('taggables', function (Blueprint $table) {\n    $table->id();\n    $table->unsignedBigInteger('tag_id');\n    $table->morphs('taggable');\n});\n\n\u002F\u002F Usage\n$post = Post::find(1);\n$post->tags()->attach([1, 2, 3]);\n\n$tag = Tag::find(1);\n$posts = $tag->posts; \u002F\u002F All posts with this tag\n```\n\n**Custom Type\u002FID Columns:**\n\n```php\n\u002F\u002F Custom column names\npublic function comments()\n{\n    return $this->morphMany(Comment::class, 'commentable', 'parent_type', 'parent_id');\n}\n\n\u002F\u002F Migration with custom names\nSchema::create('comments', function (Blueprint $table) {\n    $table->string('parent_type');\n    $table->unsignedBigInteger('parent_id');\n    $table->index(['parent_type', 'parent_id']);\n});\n```\n\n**Polymorphic with Eager Loading:**\n\n```php\n\u002F\u002F Load polymorphic relationships\n$comments = Comment::with('commentable')->get();\n\nforeach ($comments as $comment) {\n    if ($comment->commentable instanceof Post) {\n        echo \"Post: \" . $comment->commentable->title;\n    } else {\n        echo \"Video: \" . $comment->commentable->title;\n    }\n}\n```\n\n**Querying Polymorphic Relationships:**\n\n```php\n\u002F\u002F Get comments on posts only\n$postComments = Comment::where('commentable_type', Post::class)->get();\n\n\u002F\u002F With eager loading constraints\n$posts = Post::with(['comments' => function ($query) {\n    $query->latest()->limit(5);\n}])->get();\n```\n\n**Best Practices:**\n- Use for truly polymorphic data (comments, tags, likes)\n- Consider separate tables for different types if logic differs\n- Index polymorphic columns (type + id)\n- Use morph maps to avoid storing full class names\n\n**Morph Maps (Security):**\n\n```php\n\u002F\u002F AppServiceProvider\nuse Illuminate\\Database\\Eloquent\\Relations\\Relation;\n\nRelation::morphMap([\n    'post' => 'App\\Models\\Post',\n    'video' => 'App\\Models\\Video',\n]);\n\n\u002F\u002F Now stores 'post' instead of 'App\\Models\\Post'\n\u002F\u002F Prevents direct class name injection in requests\n```\n\n**Performance:** Polymorphic queries are slightly slower than regular relationships due to additional condition.\n\n**Follow-up Questions:**\n- How do you add constraints to polymorphic relationships?\n- Can you have nested polymorphic relationships?\n- How do you handle polymorphic relationships with soft deletes?",[62,284,285],"Polymorphic","Relationships",{"id":287,"category":246,"question":288,"answer":289,"level":173,"tags":290},42,"How do you implement soft deletes in Laravel?","Soft deletes allow you to \"delete\" records without removing them from the database by setting a `deleted_at` timestamp.\n\n**Setup:**\n\n```php\n\u002F\u002F Migration\nSchema::create('posts', function (Blueprint $table) {\n    $table->id();\n    $table->string('title');\n    $table->softDeletes(); \u002F\u002F Adds deleted_at column\n    $table->timestamps();\n});\n\n\u002F\u002F Add to model\nuse Illuminate\\Database\\Eloquent\\SoftDeletes;\n\nclass Post extends Model\n{\n    use SoftDeletes;\n    \n    protected $dates = ['deleted_at'];\n}\n```\n\n**Basic Usage:**\n\n```php\n\u002F\u002F Soft delete a record\n$post = Post::find(1);\n$post->delete(); \u002F\u002F Sets deleted_at timestamp\n\n\u002F\u002F Check if trashed\nif ($post->trashed()) {\n    echo \"Post is soft deleted\";\n}\n\n\u002F\u002F Force delete (permanent)\n$post->forceDelete();\n\n\u002F\u002F Restore soft deleted\n$post->restore();\n```\n\n**Querying Soft Deleted Models:**\n\n```php\n\u002F\u002F Exclude soft deleted (default)\n$posts = Post::all(); \u002F\u002F Only non-deleted\n\n\u002F\u002F Include soft deleted\n$posts = Post::withTrashed()->get();\n\n\u002F\u002F Only soft deleted\n$posts = Post::onlyTrashed()->get();\n\n\u002F\u002F Count only trashed\n$count = Post::onlyTrashed()->count();\n```\n\n**Relationships with Soft Deletes:**\n\n```php\nclass User extends Model\n{\n    use SoftDeletes;\n    \n    public function posts()\n    {\n        \u002F\u002F Include soft deleted posts\n        return $this->hasMany(Post::class)->withTrashed();\n    }\n    \n    \u002F\u002F Or only non-deleted (default)\n    public function activePosts()\n    {\n        return $this->hasMany(Post::class);\n    }\n}\n\n\u002F\u002F Query with soft deletes in relationship\n$user = User::with(['posts' => function ($query) {\n    $query->withTrashed(); \u002F\u002F Include soft deleted\n}])->find(1);\n```\n\n**Global Scopes:**\n\n```php\n\u002F\u002F Remove global scope temporarily\n$posts = Post::withoutGlobalScope('softDeletes')->get();\n\n\u002F\u002F Remove multiple scopes\n$posts = Post::withoutGlobalScopes([SoftDeletingScope::class])->get();\n```\n\n**Custom Soft Delete Column:**\n\n```php\nclass Post extends Model\n{\n    use SoftDeletes;\n    \n    const DELETED_AT = 'archived_at'; \u002F\u002F Custom column name\n    \n    \u002F\u002F Or override method\n    public function getDeletedAtColumn()\n    {\n        return 'archived_at';\n    }\n}\n```\n\n**Events with Soft Deletes:**\n\n```php\n\u002F\u002F Model events still fire\nclass Post extends Model\n{\n    use SoftDeletes;\n    \n    protected static function booted()\n    {\n        static::deleting(function ($post) {\n            if ($post->isForceDeleting()) {\n                \u002F\u002F Permanent delete\n                Log::info(\"Post {$post->id} permanently deleted\");\n            } else {\n                \u002F\u002F Soft delete\n                Log::info(\"Post {$post->id} soft deleted\");\n            }\n        });\n        \n        static::restoring(function ($post) {\n            Log::info(\"Post {$post->id} restored\");\n        });\n    }\n}\n```\n\n**Performance:** Soft deletes add a `WHERE deleted_at IS NULL` condition to queries, which should be indexed.\n\n```php\n\u002F\u002F Add index for performance\nSchema::table('posts', function (Blueprint $table) {\n    $table->index('deleted_at');\n});\n```\n\n**Best Practices:**\n- Always add `deleted_at` index for large tables\n- Use `forceDelete()` sparingly\n- Consider unique constraints with soft deletes\n- Implement cascading soft deletes manually if needed\n\n**Unique Constraints with Soft Deletes:**\n\n```php\n\u002F\u002F Allow duplicate emails for soft deleted users\nSchema::table('users', function (Blueprint $table) {\n    $table->unique(['email', 'deleted_at']);\n});\n```\n\n**Follow-up Questions:**\n- How do you handle foreign keys with soft deletes?\n- Can you restore soft deleted records with relationships?\n- How do you permanently delete old soft deleted records?",[62,291,54],"Soft Deletes",{"id":293,"category":246,"question":294,"answer":295,"level":173,"tags":296},43,"What are local and global scopes in Eloquent?","Scopes allow you to define reusable query constraints that can be chained.\n\n**Local Scopes:**\n\n```php\nclass User extends Model\n{\n    \u002F\u002F Basic scope\n    public function scopeActive($query)\n    {\n        return $query->where('is_active', true);\n    }\n    \n    \u002F\u002F With parameters\n    public function scopeRole($query, $role)\n    {\n        return $query->where('role', $role);\n    }\n    \n    \u002F\u002F Dynamic scope\n    public function scopeWhereLike($query, $column, $value)\n    {\n        return $query->where($column, 'LIKE', '%' . $value . '%');\n    }\n    \n    \u002F\u002F Complex scope\n    public function scopeRecent($query, $days = 7)\n    {\n        return $query->where('created_at', '>=', now()->subDays($days));\n    }\n}\n\n\u002F\u002F Usage\n$users = User::active()->role('admin')->get();\n$users = User::whereLike('name', 'john')->get();\n$users = User::recent(30)->get();\n```\n\n**Global Scopes:**\n\n```php\n\u002F\u002F Using anonymous global scope\nclass User extends Model\n{\n    protected static function booted()\n    {\n        static::addGlobalScope('active', function ($query) {\n            $query->where('is_active', true);\n        });\n    }\n}\n\n\u002F\u002F Using dedicated class\nclass ActiveScope implements Scope\n{\n    public function apply(Builder $builder, Model $model)\n    {\n        $builder->where('is_active', true);\n    }\n}\n\nclass User extends Model\n{\n    protected static function booted()\n    {\n        static::addGlobalScope(new ActiveScope);\n    }\n}\n```\n\n**Removing Global Scopes:**\n\n```php\n\u002F\u002F Remove all global scopes\n$users = User::withoutGlobalScopes()->get();\n\n\u002F\u002F Remove specific scope\n$users = User::withoutGlobalScope(ActiveScope::class)->get();\n\n\u002F\u002F Remove by name\n$users = User::withoutGlobalScope('active')->get();\n\n\u002F\u002F Remove multiple\n$users = User::withoutGlobalScopes([ActiveScope::class, AnotherScope::class])->get();\n```\n\n**Dynamic Global Scopes:**\n\n```php\nclass TenantScope implements Scope\n{\n    public function apply(Builder $builder, Model $model)\n    {\n        if ($tenantId = session('tenant_id')) {\n            $builder->where('tenant_id', $tenantId);\n        }\n    }\n}\n```\n\n**Scope Combinations:**\n\n```php\n\u002F\u002F Combine local scopes\n$users = User::active()->role('admin')->orderBy('name')->paginate(15);\n\n\u002F\u002F Scope with relationships\nclass Post extends Model\n{\n    public function scopePublished($query)\n    {\n        return $query->where('published_at', '\u003C=', now());\n    }\n    \n    public function scopeFromUser($query, $userId)\n    {\n        return $query->where('user_id', $userId);\n    }\n}\n\n$posts = Post::published()->fromUser(1)->get();\n```\n\n**Best Practices:**\n- Use local scopes for reusable constraints\n- Use global scopes for multi-tenant or soft deletes\n- Name scopes clearly (scopeActive, scopeRole)\n- Avoid side effects in scopes\n- Document what each scope does\n\n**Performance:** Scopes add conditions to SQL queries but don't affect performance significantly if indexed properly.\n\n**Testing Scopes:**\n\n```php\npublic function test_active_scope()\n{\n    User::factory()->create(['is_active' => true]);\n    User::factory()->create(['is_active' => false]);\n    \n    $activeUsers = User::active()->get();\n    \n    $this->assertCount(1, $activeUsers);\n    $this->assertTrue($activeUsers->first()->is_active);\n}\n```\n\n**Follow-up Questions:**\n- Can scopes accept multiple parameters?\n- How do you conditionally apply scopes?\n- What's the difference between local and global scopes?",[62,297,298],"Scopes","Query Builder",{"id":300,"category":246,"question":301,"answer":302,"level":173,"tags":303},44,"How do you handle API authentication with Laravel Sanctum?","Sanctum provides a simple API token authentication system for SPAs and mobile applications.\n\n**Installation:**\n\n```bash\ncomposer require laravel\u002Fsanctum\nphp artisan vendor:publish --provider=\"Laravel\\Sanctum\\SanctumServiceProvider\"\nphp artisan migrate\n```\n\n**Configuration:**\n\n```php\n\u002F\u002F config\u002Fsanctum.php\n'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1')),\n'expiration' => null, \u002F\u002F Token expiration in minutes\n\n\u002F\u002F In User model\nuse Laravel\\Sanctum\\HasApiTokens;\n\nclass User extends Authenticatable\n{\n    use HasApiTokens;\n}\n```\n\n**API Token Authentication:**\n\n```php\n\u002F\u002F Generate token\npublic function createToken(Request $request)\n{\n    $user = User::find(1);\n    \n    \u002F\u002F Simple token\n    $token = $user->createToken('api-token')->plainTextToken;\n    \n    \u002F\u002F Token with abilities\n    $token = $user->createToken('mobile-token', ['read-posts', 'write-posts'])->plainTextToken;\n    \n    \u002F\u002F Expiring token\n    $token = $user->createToken('temp-token', expiresAt: now()->addDay())->plainTextToken;\n    \n    return response()->json(['token' => $token]);\n}\n\n\u002F\u002F Authenticate requests\nRoute::middleware('auth:sanctum')->get('\u002Fuser', function (Request $request) {\n    return $request->user();\n});\n```\n\n**SPA Authentication (Cookie-based):**\n\n```php\n\u002F\u002F routes\u002Fapi.php\nRoute::middleware('auth:sanctum')->group(function () {\n    Route::get('\u002Fuser', function (Request $request) {\n        return $request->user();\n    });\n});\n\n\u002F\u002F Login endpoint\npublic function login(Request $request)\n{\n    if (Auth::attempt($request->only('email', 'password'))) {\n        $request->session()->regenerate();\n        return response()->json(Auth::user());\n    }\n    \n    return response()->json(['error' => 'Invalid credentials'], 401);\n}\n\n\u002F\u002F Logout\npublic function logout(Request $request)\n{\n    Auth::guard('web')->logout();\n    $request->session()->invalidate();\n    $request->session()->regenerateToken();\n    \n    return response()->json(['message' => 'Logged out']);\n}\n```\n\n**Token Abilities:**\n\n```php\n\u002F\u002F Check abilities\nif ($user->tokenCan('read-posts')) {\n    \u002F\u002F User can read posts\n}\n\n\u002F\u002F Middleware for abilities\nRoute::post('\u002Fposts', function () {\n    \u002F\u002F\n})->middleware('auth:sanctum')->middleware('abilities:write-posts');\n```\n\n**Revoking Tokens:**\n\n```php\n\u002F\u002F Revoke all tokens\n$user->tokens()->delete();\n\n\u002F\u002F Revoke current token\n$request->user()->currentAccessToken()->delete();\n\n\u002F\u002F Revoke specific token\n$user->tokens()->where('id', $tokenId)->delete();\n\n\u002F\u002F Revoke tokens by name\n$user->tokens()->where('name', 'mobile')->delete();\n```\n\n**Custom Token Model:**\n\n```php\n\u002F\u002F Create custom token model\nuse Laravel\\Sanctum\\PersonalAccessToken;\n\nclass CustomToken extends PersonalAccessToken\n{\n    \u002F\u002F Add custom methods\n}\n\n\u002F\u002F Configure in sanctum config\n'personal_access_token_model' => CustomToken::class,\n```\n\n**Testing with Sanctum:**\n\n```php\npublic function test_authenticated_api()\n{\n    $user = User::factory()->create();\n    \n    $response = $this->actingAs($user)->getJson('\u002Fapi\u002Fuser');\n    $response->assertStatus(200);\n    \n    \u002F\u002F Or with token\n    $token = $user->createToken('test')->plainTextToken;\n    $response = $this->withHeaders(['Authorization' => 'Bearer ' . $token])\n        ->getJson('\u002Fapi\u002Fuser');\n}\n```\n\n**Best Practices:**\n- Use short-lived tokens for mobile apps\n- Use cookie-based auth for SPAs on same domain\n- Implement token refresh mechanism\n- Store tokens securely (HTTPS only)\n- Monitor and revoke suspicious tokens\n\n**Security Considerations:**\n- Rotate tokens periodically\n- Limit token abilities\n- Implement rate limiting on token creation\n- Log token creation and usage\n\n**Performance:** Sanctum uses database for token storage; index the `token` column.\n\n**Follow-up Questions:**\n- What's the difference between Sanctum and Passport?\n- How do you handle token expiration and refresh?\n- Can Sanctum work with mobile apps?",[185,304,305,80],"API Authentication","Tokens",{"id":307,"category":246,"question":308,"answer":309,"level":173,"tags":310},45,"How do you use Laravel's task scheduling?","Laravel's task scheduler allows you to define scheduled tasks within the application code instead of using cron.\n\n**Basic Scheduling (Laravel 11+):**\n\n```php\n\u002F\u002F bootstrap\u002Fapp.php\n->withSchedule(function ($schedule) {\n    \u002F\u002F Artisan commands\n    $schedule->command('emails:send')->daily();\n    $schedule->command('users:deactivate')->hourly();\n    \n    \u002F\u002F Closures\n    $schedule->call(function () {\n        DB::table('recent_users')->delete();\n    })->daily();\n    \n    \u002F\u002F Shell commands\n    $schedule->exec('node script.js')->everyMinute();\n    \n    \u002F\u002F Job dispatching\n    $schedule->job(new ProcessPodcast)->everyFiveMinutes();\n})\n```\n\n**Schedule Frequencies:**\n\n```php\n$schedule->command('backup:run')->cron('* * * * *');\n$schedule->command('backup:run')->everyMinute();\n$schedule->command('backup:run')->everyTwoMinutes();\n$schedule->command('backup:run')->everyFiveMinutes();\n$schedule->command('backup:run')->everyTenMinutes();\n$schedule->command('backup:run')->everyFifteenMinutes();\n$schedule->command('backup:run')->everyThirtyMinutes();\n$schedule->command('backup:run')->hourly();\n$schedule->command('backup:run')->hourlyAt(17);\n$schedule->command('backup:run')->everyTwoHours();\n$schedule->command('backup:run')->daily();\n$schedule->command('backup:run')->dailyAt('13:00');\n$schedule->command('backup:run')->twiceDaily(1, 13);\n$schedule->command('backup:run')->weekly();\n$schedule->command('backup:run')->weeklyOn(1, '8:00');\n$schedule->command('backup:run')->monthly();\n$schedule->command('backup:run')->monthlyOn(4, '15:00');\n$schedule->command('backup:run')->quarterly();\n$schedule->command('backup:run')->yearly();\n$schedule->command('backup:run')->days([1, 3, 5]); \u002F\u002F Monday, Wednesday, Friday\n```\n\n**Constraints:**\n\n```php\n$schedule->command('report:generate')\n    ->daily()\n    ->between('8:00', '17:00')\n    ->when(function () {\n        return !app()->environment('production');\n    })\n    ->skip(function () {\n        return cache()->get('maintenance_mode');\n    });\n```\n\n**Running Single Server:**\n\n```php\n$schedule->command('email:send')\n    ->daily()\n    ->onOneServer(); \u002F\u002F Prevents overlapping on multiple servers\n```\n\n**Output Handling:**\n\n```php\n$schedule->command('backup:run')\n    ->daily()\n    ->sendOutputTo(storage_path('logs\u002Fbackup.log'))\n    ->emailOutputTo('admin@example.com')\n    ->emailOutputOnFailure('alerts@example.com');\n```\n\n**Environments:**\n\n```php\n$schedule->command('analytics:process')\n    ->hourly()\n    ->environments(['production']); \u002F\u002F Only runs in production\n```\n\n**Maintenance Mode:**\n\n```php\n$schedule->command('backup:run')\n    ->daily()\n    ->evenInMaintenanceMode(); \u002F\u002F Run even when app is down\n```\n\n**Task Hooks:**\n\n```php\n$schedule->command('email:send')\n    ->daily()\n    ->before(function () {\n        Log::info('Starting email send');\n    })\n    ->after(function () {\n        Log::info('Finished email send');\n    })\n    ->onSuccess(function () {\n        Log::info('Email send completed successfully');\n    })\n    ->onFailure(function () {\n        Log::error('Email send failed');\n    });\n```\n\n**Ping URLs:**\n\n```php\n$schedule->command('backup:run')\n    ->daily()\n    ->pingBefore('https:\u002F\u002Fhealthcheck.example.com\u002Fstarting')\n    ->thenPing('https:\u002F\u002Fhealthcheck.example.com\u002Fcompleted')\n    ->pingOnSuccess('https:\u002F\u002Fhealthcheck.example.com\u002Fsuccess')\n    ->pingOnFailure('https:\u002F\u002Fhealthcheck.example.com\u002Ffailure');\n```\n\n**Running the Scheduler:**\n\n```bash\n# Add to server crontab\n* * * * * cd \u002Fpath-to-project && php artisan schedule:run >> \u002Fdev\u002Fnull 2>&1\n\n# Test locally\nphp artisan schedule:list\nphp artisan schedule:run\n```\n\n**Common Mistakes:**\n- Forgetting to add cron entry\n- Tasks taking longer than frequency (overlapping)\n- Not handling failures\n- Using `onOneServer()` without proper cache driver\n\n**Best Practices:**\n- Keep tasks short and idempotent\n- Use `onOneServer()` for critical tasks\n- Log task execution and failures\n- Monitor task health\n- Use queued jobs for long-running tasks\n\n**Performance:** Tasks run in separate processes; long-running tasks should be queued.\n\n**Follow-up Questions:**\n- How do you prevent task overlap?\n- How do you test scheduled tasks?\n- What's the difference between `schedule:run` and `schedule:work`?",[32,311,312],"Cron","Automation",{"id":314,"category":246,"question":315,"answer":316,"level":173,"tags":317},46,"How do you handle file storage with multiple disks in Laravel?","Laravel's filesystem provides a unified API for local and cloud storage services.\n\n**Configuration:**\n\n```php\n\u002F\u002F config\u002Ffilesystems.php\n'disks' => [\n    'local' => [\n        'driver' => 'local',\n        'root' => storage_path('app'),\n        'throw' => false,\n    ],\n    'public' => [\n        'driver' => 'local',\n        'root' => storage_path('app\u002Fpublic'),\n        'url' => env('APP_URL').'\u002Fstorage',\n        'visibility' => 'public',\n    ],\n    's3' => [\n        'driver' => 's3',\n        'key' => env('AWS_ACCESS_KEY_ID'),\n        'secret' => env('AWS_SECRET_ACCESS_KEY'),\n        'region' => env('AWS_DEFAULT_REGION'),\n        'bucket' => env('AWS_BUCKET'),\n        'url' => env('AWS_URL'),\n        'endpoint' => env('AWS_ENDPOINT'),\n    ],\n],\n```\n\n**Basic Operations:**\n\n```php\nuse Illuminate\\Support\\Facades\\Storage;\n\n\u002F\u002F Default disk\nStorage::put('file.txt', 'content');\n\n\u002F\u002F Specific disk\nStorage::disk('s3')->put('file.txt', 'content');\n\n\u002F\u002F Get file\n$content = Storage::get('file.txt');\n\n\u002F\u002F Check if exists\nif (Storage::exists('file.txt')) { }\n\n\u002F\u002F Delete\nStorage::delete('file.txt');\n\n\u002F\u002F Delete multiple\nStorage::delete(['file1.txt', 'file2.txt']);\n```\n\n**File Uploads:**\n\n```php\n\u002F\u002F Store uploaded file\n$path = $request->file('avatar')->store('avatars', 's3');\n\n\u002F\u002F Store with custom name\n$path = $request->file('avatar')->storeAs('avatars', 'user_1.jpg', 's3');\n\n\u002F\u002F Get URL\n$url = Storage::disk('s3')->url($path);\n\n\u002F\u002F Get temporary URL (for private files)\n$url = Storage::disk('s3')->temporaryUrl(\n    $path, now()->addMinutes(5)\n);\n```\n\n**Directories:**\n\n```php\n\u002F\u002F Create directory\nStorage::makeDirectory('photos');\n\n\u002F\u002F Delete directory\nStorage::deleteDirectory('photos');\n\n\u002F\u002F Get all files\n$files = Storage::files('photos');\n\n\u002F\u002F Get all files recursively\n$files = Storage::allFiles('photos');\n\n\u002F\u002F Get directories\n$directories = Storage::directories('photos');\n\n\u002F\u002F Get all directories recursively\n$directories = Storage::allDirectories('photos');\n```\n\n**File Information:**\n\n```php\n\u002F\u002F Size in bytes\n$size = Storage::size('file.txt');\n\n\u002F\u002F Last modified timestamp\n$time = Storage::lastModified('file.txt');\n\n\u002F\u002F MIME type\n$mime = Storage::mimeType('file.txt');\n\n\u002F\u002F Path\n$path = Storage::path('file.txt'); \u002F\u002F Local only\n```\n\n**Visibility:**\n\n```php\n\u002F\u002F Set visibility\nStorage::put('public.txt', 'content', 'public');\nStorage::put('private.txt', 'content', 'private');\n\n\u002F\u002F Change visibility\nStorage::setVisibility('private.txt', 'public');\n\n\u002F\u002F Get visibility\n$visibility = Storage::getVisibility('file.txt');\n```\n\n**Custom Filesystem Drivers:**\n\n```php\n\u002F\u002F AppServiceProvider\nuse Illuminate\\Support\\Facades\\Storage;\n\npublic function boot()\n{\n    Storage::extend('dropbox', function ($app, $config) {\n        return new DropboxAdapter(\n            new DropboxClient($config['token'])\n        );\n    });\n}\n```\n\n**Streaming Large Files:**\n\n```php\n\u002F\u002F Download large file\nreturn Storage::disk('s3')->download('large.zip');\n\n\u002F\u002F Stream to response\nreturn response()->stream(function () {\n    $stream = Storage::disk('s3')->readStream('file.mp4');\n    fpassthru($stream);\n    fclose($stream);\n}, 200, ['Content-Type' => 'video\u002Fmp4']);\n```\n\n**Best Practices:**\n- Use separate disks for different file types\n- Set appropriate visibility (public\u002Fprivate)\n- Use temporary URLs for private files\n- Implement file cleanup schedules\n- Validate files before storing\n\n**Security:**\n- Never trust user-provided filenames\n- Sanitize file names\n- Validate file types and sizes\n- Use signed URLs for sensitive files\n\n**Performance:**\n- Use streaming for large files\n- Implement caching for frequently accessed files\n- Use CDN for public files\n\n**Follow-up Questions:**\n- How do you handle file versioning?\n- How do you synchronize files across disks?\n- What's the difference between `put` and `putFile`?",[116,318,319],"Filesystem","Cloud Storage",{"id":321,"category":246,"question":322,"answer":323,"level":173,"tags":324},47,"How do you implement caching in Laravel?","Laravel's cache system provides a unified API for various cache backends to store and retrieve data.\n\n**Configuration:**\n\n```php\n\u002F\u002F config\u002Fcache.php\n'default' => env('CACHE_DRIVER', 'redis'),\n\n'stores' => [\n    'file' => [\n        'driver' => 'file',\n        'path' => storage_path('framework\u002Fcache\u002Fdata'),\n    ],\n    'redis' => [\n        'driver' => 'redis',\n        'connection' => 'cache',\n    ],\n    'memcached' => [\n        'driver' => 'memcached',\n        'servers' => [\n            ['host' => '127.0.0.1', 'port' => 11211],\n        ],\n    ],\n],\n```\n\n**Basic Cache Operations:**\n\n```php\nuse Illuminate\\Support\\Facades\\Cache;\n\n\u002F\u002F Store\nCache::put('key', 'value', 3600); \u002F\u002F seconds\nCache::put('key', 'value', now()->addHour());\n\n\u002F\u002F Store forever\nCache::forever('key', 'value');\n\n\u002F\u002F Get with default\n$value = Cache::get('key', 'default');\n$value = Cache::get('key', function () {\n    return 'default';\n});\n\n\u002F\u002F Get or store (remember)\n$users = Cache::remember('users', 3600, function () {\n    return User::all();\n});\n\n\u002F\u002F Get or store forever\n$users = Cache::rememberForever('users', function () {\n    return User::all();\n});\n\n\u002F\u002F Check if exists\nif (Cache::has('key')) { }\n\n\u002F\u002F Increment\u002FDecrement\nCache::increment('counter');\nCache::increment('counter', 5);\nCache::decrement('counter', 2);\n\n\u002F\u002F Delete\nCache::forget('key');\nCache::flush(); \u002F\u002F Delete all\n```\n\n**Cache Tags (Redis\u002FMemcached):**\n\n```php\n\u002F\u002F Store with tags\nCache::tags(['users', 'active'])->put('user:1', $user, 3600);\n\n\u002F\u002F Retrieve\n$user = Cache::tags(['users'])->get('user:1');\n\n\u002F\u002F Flush by tag\nCache::tags('users')->flush();\nCache::tags(['users', 'active'])->flush();\n```\n\n**Cache Locking:**\n\n```php\n$lock = Cache::lock('processing', 10);\n\nif ($lock->get()) {\n    \u002F\u002F Process something\n    \n    $lock->release();\n}\n\n\u002F\u002F Blocking lock\n$lock->block(5); \u002F\u002F Wait up to 5 seconds\n```\n\n**Atomic Locks:**\n\n```php\nCache::lock('import', 60)->get(function () {\n    \u002F\u002F Only one process can run this at a time\n});\n```\n\n**Cache Helper Functions:**\n\n```php\n\u002F\u002F Using cache() helper\ncache(['key' => 'value'], 3600);\n$value = cache('key');\ncache()->put('key', 'value', 3600);\n```\n\n**Real-World Examples:**\n\n```php\n\u002F\u002F Cache expensive queries\nclass UserController\n{\n    public function show($id)\n    {\n        $user = Cache::remember(\"user:{$id}\", 3600, function () use ($id) {\n            return User::with('posts')->findOrFail($id);\n        });\n        \n        return view('users.show', compact('user'));\n    }\n    \n    public function update($id, Request $request)\n    {\n        $user = User::findOrFail($id);\n        $user->update($request->validated());\n        \n        \u002F\u002F Invalidate cache\n        Cache::forget(\"user:{$id}\");\n        \n        return redirect()->route('users.show', $id);\n    }\n}\n\n\u002F\u002F Cache API responses\nRoute::middleware('cache.headers:public;max_age=3600;etag')->get('\u002Fapi\u002Fusers', function () {\n    return User::all();\n});\n```\n\n**Cache Events:**\n\n```php\n\u002F\u002F Listen for cache events\nCache::macro('cacheHit', function ($key) {\n    Log::info(\"Cache hit: {$key}\");\n});\n```\n\n**Custom Cache Drivers:**\n\n```php\n\u002F\u002F AppServiceProvider\nuse Illuminate\\Support\\Facades\\Cache;\n\npublic function boot()\n{\n    Cache::extend('custom', function ($app) {\n        return Cache::repository(new CustomStore);\n    });\n}\n```\n\n**Best Practices:**\n- Cache expensive operations only\n- Set appropriate TTL (Time To Live)\n- Invalidate cache when data changes\n- Use tags for grouped invalidation\n- Cache whole responses when possible\n- Monitor cache hit ratio\n\n**Cache Strategies:**\n\n| Strategy | When to Use |\n|----------|-------------|\n| Write-through | Data that must be consistent |\n| Write-behind | High write throughput |\n| Cache-aside | Most common, simple |\n| Refresh-ahead | Predictable access patterns |\n\n**Performance:**\n- Redis: 50,000+ ops\u002Fsec\n- Memcached: 40,000+ ops\u002Fsec\n- File: 5,000 ops\u002Fsec\n- Array: 100,000+ ops\u002Fsec (request only)\n\n**Common Mistakes:**\n- Caching too much or too little\n- Not invalidating stale cache\n- Using file cache in production\n- Caching user-specific data globally\n\n**Security:** Never cache sensitive user data without encryption.\n\n**Follow-up Questions:**\n- How do you implement cache warming?\n- What's the difference between Redis and Memcached?\n- How do you handle cache stampedes?",[325,243,326,327],"Caching","Redis","Memcached",{"id":329,"category":246,"question":330,"answer":331,"level":173,"tags":332},48,"How do you handle email sending and notifications in Laravel?","Laravel provides a clean API for sending email via various drivers and a notification system for multi-channel notifications.\n\n**Mail Configuration:**\n\n```php\n\u002F\u002F config\u002Fmail.php\n'default' => env('MAIL_MAILER', 'smtp'),\n\n'mailers' => [\n    'smtp' => [\n        'transport' => 'smtp',\n        'host' => env('MAIL_HOST', 'smtp.mailgun.org'),\n        'port' => env('MAIL_PORT', 587),\n        'encryption' => env('MAIL_ENCRYPTION', 'tls'),\n        'username' => env('MAIL_USERNAME'),\n        'password' => env('MAIL_PASSWORD'),\n    ],\n    'mailgun' => [\n        'transport' => 'mailgun',\n        'domain' => env('MAILGUN_DOMAIN'),\n        'secret' => env('MAILGUN_SECRET'),\n    ],\n],\n```\n\n**Creating Mailables:**\n\n```bash\nphp artisan make:mail WelcomeMail\n```\n\n```php\n\u002F\u002F app\u002FMail\u002FWelcomeMail.php\nuse Illuminate\\Bus\\Queueable;\nuse Illuminate\\Mail\\Mailable;\nuse Illuminate\\Mail\\Mailables\\Content;\nuse Illuminate\\Mail\\Mailables\\Envelope;\n\nclass WelcomeMail extends Mailable\n{\n    use Queueable;\n    \n    public function __construct(public User $user) {}\n    \n    public function envelope(): Envelope\n    {\n        return new Envelope(\n            subject: 'Welcome to Our App',\n            tags: ['welcome'],\n            metadata: ['user_id' => $this->user->id],\n        );\n    }\n    \n    public function content(): Content\n    {\n        return new Content(\n            view: 'emails.welcome',\n            with: ['name' => $this->user->name],\n        );\n    }\n    \n    public function attachments(): array\n    {\n        return [];\n    }\n}\n\n\u002F\u002F Sending\nMail::to($user->email)->send(new WelcomeMail($user));\nMail::to('admin@example.com')->queue(new WelcomeMail($user)); \u002F\u002F Queue\n```\n\n**Markdown Mail:**\n\n```bash\nphp artisan make:mail OrderShipped --markdown=emails.orders.shipped\n```\n\n```blade\n{{-- resources\u002Fviews\u002Femails\u002Forders\u002Fshipped.blade.php --}}\n\u003Cx-mail::message>\n# Order Shipped\n\nYour order has been shipped!\n\n**Order ID:** {{ $order->id }}\n**Tracking Number:** {{ $order->tracking_number }}\n\n\u003Cx-mail::button :url=\"$url\">\nTrack Order\n\u003C\u002Fx-mail::button>\n\nThanks,\u003Cbr>\n{{ config('app.name') }}\n\u003C\u002Fx-mail::message>\n```\n\n**Notifications:**\n\n```bash\nphp artisan make:notification OrderPaid\n```\n\n```php\n\u002F\u002F app\u002FNotifications\u002FOrderPaid.php\nuse Illuminate\\Bus\\Queueable;\nuse Illuminate\\Notifications\\Notification;\nuse Illuminate\\Notifications\\Messages\\MailMessage;\n\nclass OrderPaid extends Notification\n{\n    use Queueable;\n    \n    public function __construct(public Order $order) {}\n    \n    public function via($notifiable): array\n    {\n        return ['mail', 'database', 'broadcast'];\n    }\n    \n    public function toMail($notifiable): MailMessage\n    {\n        return (new MailMessage)\n            ->subject('Order Paid')\n            ->line('Your order has been paid.')\n            ->action('View Order', url('\u002Forders\u002F' . $this->order->id))\n            ->line('Thank you for your business!');\n    }\n    \n    public function toDatabase($notifiable): array\n    {\n        return [\n            'order_id' => $this->order->id,\n            'amount' => $this->order->total,\n            'message' => 'Order #' . $this->order->id . ' has been paid',\n        ];\n    }\n    \n    public function toBroadcast($notifiable): BroadcastMessage\n    {\n        return new BroadcastMessage([\n            'order_id' => $this->order->id,\n            'message' => 'Order paid',\n        ]);\n    }\n}\n\n\u002F\u002F Sending notification\n$user->notify(new OrderPaid($order));\n\n\u002F\u002F Broadcast to multiple channels\nNotification::send($users, new OrderPaid($order));\n```\n\n**Custom Channels (SMS, Slack):**\n\n```php\n\u002F\u002F Slack notification\npublic function toSlack($notifiable)\n{\n    return (new SlackMessage)\n        ->content('Order #' . $this->order->id . ' has been paid!');\n}\n\n\u002F\u002F SMS with Vonage\u002FNexmo\npublic function toVonage($notifiable)\n{\n    return (new VonageMessage)\n        ->content('Your order has been paid!');\n}\n```\n\n**On-Demand Notifications:**\n\n```php\nNotification::route('mail', 'user@example.com')\n    ->route('slack', 'https:\u002F\u002Fhooks.slack.com\u002F...')\n    ->notify(new OrderPaid($order));\n```\n\n**Mail Preview in Browser:**\n\n```php\n\u002F\u002F routes\u002Fweb.php\nRoute::get('\u002Fmail\u002Fpreview', function () {\n    return new App\\Mail\\WelcomeMail(User::first());\n});\n```\n\n**Email Verification:**\n\n```php\n\u002F\u002F User model\nuse Illuminate\\Contracts\\Auth\\MustVerifyEmail;\n\nclass User extends Authenticatable implements MustVerifyEmail\n{\n    \u002F\u002F\n}\n\n\u002F\u002F Routes\nRoute::get('\u002Femail\u002Fverify', [VerificationController::class, 'notice'])\n    ->middleware('auth')->name('verification.notice');\n```\n\n**Best Practices:**\n- Queue email sending for better performance\n- Use markdown mail for consistent styling\n- Implement rate limiting for notifications\n- Log all email sends for debugging\n- Test emails with mailtrap in development\n\n**Performance:** Queue email sending to avoid blocking responses.\n\n**Security:**\n- Never include sensitive data in emails\n- Use signed URLs for email links\n- Implement unsubscribe mechanism\n- Validate email addresses before sending\n\n**Follow-up Questions:**\n- How do you handle email bounces and complaints?\n- How do you localize notification content?\n- What's the difference between mail and notification?",[333,334,335,336],"Mail","Notifications","Email","Channels",[338,347,354,361,369,378,386,394,402,409,418,427,436,444,452,461,468],{"id":339,"category":340,"question":341,"answer":342,"level":343,"tags":344},21,"REST API","What are the best practices for building REST APIs in Laravel?","Building production-ready REST APIs requires following established best practices for consistency, security, and performance.\n\n**1. API Versioning:**\n\n```php\n\u002F\u002F routes\u002Fapi.php\nRoute::prefix('v1')->group(function () {\n    Route::apiResource('users', V1\\UserController::class);\n    Route::apiResource('posts', V1\\PostController::class);\n});\n\nRoute::prefix('v2')->group(function () {\n    Route::apiResource('users', V2\\UserController::class);\n});\n\n\u002F\u002F Or via header\nRoute::group([\n    'middleware' => 'api.version:1',\n    'namespace' => 'App\\Http\\Controllers\\Api\\V1',\n], function () {\n    Route::apiResource('users', 'UserController');\n});\n```\n\n**2. API Resources (Transformers):**\n\n```php\nclass UserResource extends JsonResource\n{\n    public function toArray(Request $request): array\n    {\n        return [\n            'id' => $this->id,\n            'name' => $this->name,\n            'email' => $this->email,\n            'avatar' => $this->avatar_url,\n            'created_at' => $this->created_at->toISOString(),\n            'updated_at' => $this->updated_at->toISOString(),\n\n            \u002F\u002F Conditional attributes\n            'email_verified_at' => $this->when($request->user()->isAdmin(), $this->email_verified_at),\n\n            \u002F\u002F Relationships\n            'posts' => PostResource::collection($this->whenLoaded('posts')),\n            'posts_count' => $this->whenCounted('posts'),\n\n            \u002F\u002F Additional metadata\n            'links' => [\n                'self' => route('api.v1.users.show', $this->id),\n                'edit' => route('api.v1.users.edit', $this->id),\n            ],\n        ];\n    }\n\n    public function with(Request $request): array\n    {\n        return [\n            'meta' => [\n                'version' => '1.0',\n                'copyright' => '2024',\n            ],\n        ];\n    }\n}\n\n\u002F\u002F Collection resource\nclass UserCollection extends ResourceCollection\n{\n    public function toArray(Request $request): array\n    {\n        return [\n            'data' => UserResource::collection($this->collection),\n            'meta' => [\n                'total' => $this->resource->total(),\n                'per_page' => $this->resource->perPage(),\n                'current_page' => $this->resource->currentPage(),\n                'last_page' => $this->resource->lastPage(),\n            ],\n            'links' => [\n                'first' => $this->resource->url(1),\n                'last' => $this->resource->url($this->resource->lastPage()),\n                'prev' => $this->resource->previousPageUrl(),\n                'next' => $this->resource->nextPageUrl(),\n            ],\n        ];\n    }\n}\n```\n\n**3. Consistent Response Format:**\n\n```php\n\u002F\u002F Trait for consistent responses\ntrait ApiResponse\n{\n    protected function success($data = null, $message = null, $code = 200)\n    {\n        return response()->json([\n            'success' => true,\n            'message' => $message,\n            'data' => $data,\n        ], $code);\n    }\n\n    protected function error($message, $code = 400, $errors = null)\n    {\n        $response = [\n            'success' => false,\n            'message' => $message,\n        ];\n\n        if ($errors) {\n            $response['errors'] = $errors;\n        }\n\n        return response()->json($response, $code);\n    }\n\n    protected function paginated($data, $message = null)\n    {\n        return response()->json([\n            'success' => true,\n            'message' => $message,\n            'data' => $data->items(),\n            'meta' => [\n                'current_page' => $data->currentPage(),\n                'last_page' => $data->lastPage(),\n                'per_page' => $data->perPage(),\n                'total' => $data->total(),\n            ],\n        ]);\n    }\n\n    protected function created($data = null, $message = 'Resource created successfully')\n    {\n        return $this->success($data, $message, 201);\n    }\n\n    protected function noContent()\n    {\n        return response()->json(null, 204);\n    }\n}\n```\n\n**4. Rate Limiting:**\n\n```php\n\u002F\u002F AppServiceProvider\nuse Illuminate\\Cache\\RateLimiting\\Limit;\nuse Illuminate\\Support\\Facades\\RateLimiter;\n\nRateLimiter::for('api', function (Request $request) {\n    return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());\n});\n\nRateLimiter::for('auth', function (Request $request) {\n    return Limit::perMinute(5)->by($request->ip());\n});\n\nRateLimiter::for('uploads', function (Request $request) {\n    return Limit::perMinute(10)->by($request->user()->id);\n});\n\n\u002F\u002F In routes\nRoute::middleware(['throttle:api'])->group(function () {\n    Route::apiResource('users', UserController::class);\n});\n\n\u002F\u002F Dynamic rate limiting\nRoute::post('\u002Fupload', [UploadController::class, 'store'])\n    ->middleware(['throttle:uploads']);\n```\n\n**5. Pagination:**\n\n```php\nclass UserController extends Controller\n{\n    use ApiResponse;\n\n    public function index(Request $request)\n    {\n        $users = User::query()\n            ->when($request->has('search'), function ($query) use ($request) {\n                $query->where('name', 'like', '%' . $request->search . '%');\n            })\n            ->when($request->has('sort'), function ($query) use ($request) {\n                $query->orderBy($request->sort, $request->get('direction', 'asc'));\n            })\n            ->paginate($request->get('per_page', 15));\n\n        return $this->paginated($users);\n    }\n}\n\n\u002F\u002F Custom pagination\n$users = User::cursorPaginate(15); \u002F\u002F For large datasets\n```\n\n**6. Exception Handling:**\n\n```php\n\u002F\u002F bootstrap\u002Fapp.php\n->withExceptions(function (Exceptions $exceptions) {\n    $exceptions->render(function (NotFoundHttpException $e, Request $request) {\n        if ($request->is('api\u002F*')) {\n            return response()->json([\n                'success' => false,\n                'message' => 'Resource not found',\n                'errors' => ['resource' => ['The requested resource does not exist']]\n            ], 404);\n        }\n    });\n\n    $exceptions->render(function (ValidationException $e, Request $request) {\n        if ($request->is('api\u002F*')) {\n            return response()->json([\n                'success' => false,\n                'message' => 'Validation failed',\n                'errors' => $e->errors()\n            ], 422);\n        }\n    });\n\n    $exceptions->render(function (AuthenticationException $e, Request $request) {\n        return response()->json([\n            'success' => false,\n            'message' => 'Unauthenticated',\n        ], 401);\n    });\n\n    $exceptions->render(function (AuthorizationException $e, Request $request) {\n        return response()->json([\n            'success' => false,\n            'message' => 'Unauthorized',\n        ], 403);\n    });\n})\n```\n\n**7. Validation with Form Requests:**\n\n```php\nclass StoreUserRequest extends FormRequest\n{\n    public function authorize(): bool\n    {\n        return auth()->check();\n    }\n\n    public function rules(): array\n    {\n        return [\n            'name' => 'required|string|max:255',\n            'email' => 'required|email|unique:users',\n            'password' => 'required|string|min:8|confirmed',\n            'profile' => 'sometimes|array',\n            'profile.bio' => 'nullable|string|max:1000',\n        ];\n    }\n\n    public function messages(): array\n    {\n        return [\n            'name.required' => 'The name field is required.',\n            'email.unique' => 'This email is already registered.',\n        ];\n    }\n\n    protected function prepareForValidation(): void\n    {\n        $this->merge([\n            'email' => strtolower($this->email),\n        ]);\n    }\n}\n```\n\n**8. API Authentication:**\n\n```php\n\u002F\u002F Sanctum for API tokens\nuse Laravel\\Sanctum\\HasApiTokens;\n\nclass User extends Authenticatable\n{\n    use HasApiTokens;\n}\n\n\u002F\u002F Generate token\n$token = $user->createToken('api-token', ['read', 'write'])->plainTextToken;\n\n\u002F\u002F Revoke token\n$user->tokens()->delete();\n\n\u002F\u002F Authenticate requests\nRoute::middleware('auth:sanctum')->get('\u002Fuser', function (Request $request) {\n    return $request->user();\n});\n```\n\n**9. Filtering, Sorting, and Searching:**\n\n```php\nclass UserController extends Controller\n{\n    public function index(Request $request)\n    {\n        $query = User::query();\n\n        \u002F\u002F Filtering\n        if ($request->has('role')) {\n            $query->where('role', $request->role);\n        }\n\n        if ($request->has('is_active')) {\n            $query->where('is_active', $request->boolean('is_active'));\n        }\n\n        \u002F\u002F Date range filtering\n        if ($request->has('created_from')) {\n            $query->where('created_at', '>=', $request->created_from);\n        }\n\n        if ($request->has('created_to')) {\n            $query->where('created_at', '\u003C=', $request->created_to);\n        }\n\n        \u002F\u002F Searching\n        if ($request->has('search')) {\n            $search = $request->search;\n            $query->where(function ($q) use ($search) {\n                $q->where('name', 'like', \"%{$search}%\")\n                  ->orWhere('email', 'like', \"%{$search}%\");\n            });\n        }\n\n        \u002F\u002F Sorting\n        if ($request->has('sort')) {\n            $sortField = $request->sort;\n            $sortDirection = $request->get('direction', 'asc');\n            $query->orderBy($sortField, $sortDirection);\n        }\n\n        \u002F\u002F Eager loading\n        $query->with(['posts' => function ($q) {\n            $q->latest()->limit(5);\n        }]);\n\n        return UserResource::collection($query->paginate());\n    }\n}\n```\n\n**10. Caching:**\n\n```php\nclass UserController extends Controller\n{\n    public function show($id)\n    {\n        $user = Cache::remember(\"user:{$id}\", 3600, function () use ($id) {\n            return User::with('posts')->findOrFail($id);\n        });\n\n        return new UserResource($user);\n    }\n\n    public function update(UpdateUserRequest $request, $id)\n    {\n        $user = User::findOrFail($id);\n        $user->update($request->validated());\n\n        \u002F\u002F Invalidate cache\n        Cache::forget(\"user:{$id}\");\n\n        return new UserResource($user);\n    }\n}\n```\n\n**11. API Documentation:**\n\n```php\n\u002F\u002F Using OpenAPI annotations\n\u002F**\n * @OA\\Get(\n *     path=\"\u002Fapi\u002Fv1\u002Fusers\",\n *     summary=\"Get list of users\",\n *     tags={\"Users\"},\n *     @OA\\Parameter(\n *         name=\"page\",\n *         in=\"query\",\n *         description=\"Page number\",\n *         required=false,\n *         @OA\\Schema(type=\"integer\")\n *     ),\n *     @OA\\Response(\n *         response=200,\n *         description=\"Successful operation\",\n *         @OA\\JsonContent(ref=\"#\u002Fcomponents\u002Fschemas\u002FUserCollection\")\n *     )\n * )\n *\u002F\npublic function index()\n{\n    \u002F\u002F Implementation\n}\n```\n\n**Best Practices Summary:**\n- Use proper HTTP methods and status codes\n- Implement rate limiting for public APIs\n- Version your API from the start\n- Use API resources for response transformation\n- Validate all input data\n- Implement proper error handling\n- Use pagination for collections\n- Document your API\n- Cache responses when appropriate\n- Use HTTPS in production\n- Implement logging for debugging\n\n**Common Mistakes:**\n- Exposing internal database IDs\n- Not handling validation errors properly\n- Missing authentication for sensitive endpoints\n- Over-fetching or under-fetching data\n- Not using HTTP caching headers\n- Inconsistent error responses\n\n**Security Considerations:**\n- Always validate and sanitize input\n- Implement rate limiting to prevent abuse\n- Use HTTPS in production\n- Implement proper authentication\n- Avoid exposing sensitive data\n- Use CORS properly\n\n**Performance Tips:**\n- Use eager loading to prevent N+1\n- Implement caching for frequent queries\n- Use pagination for large datasets\n- Compress responses\n- Use Redis for caching\n\n**Follow-up Questions:**\n- How do you handle file uploads in API?\n- What's your strategy for API version deprecation?\n- How do you test API endpoints?\n- How do you handle API monitoring and logging?","advanced",[340,345,346,80],"Best Practices","API Design",{"id":348,"category":20,"question":349,"answer":350,"level":343,"tags":351},22,"When should you use Controllers vs Services vs Actions in Laravel?","Understanding when to use each pattern is crucial for clean, maintainable architecture.\n\n**Controllers (HTTP Layer):**\nHandle HTTP requests\u002Fresponses, validation, and orchestration.\n\n```php\n\u002F\u002F Thin Controller - Just handles HTTP concerns\nclass OrderController extends Controller\n{\n    public function __construct(\n        private OrderService $orderService,\n        private OrderResource $resource\n    ) {}\n\n    public function store(StoreOrderRequest $request)\n    {\n        \u002F\u002F Validate, call service, return response\n        $order = $this->orderService->createOrder($request->validated());\n\n        return $this->resource->make($order)\n            ->response()\n            ->setStatusCode(201);\n    }\n\n    public function update(UpdateOrderRequest $request, Order $order)\n    {\n        $this->orderService->updateOrder($order, $request->validated());\n\n        return response()->noContent();\n    }\n}\n```\n\n**Services (Business Logic Layer):**\nEncapsulate complex business logic, coordinate multiple operations, and can be reused.\n\n```php\n\u002F\u002F Service - Contains business rules and workflows\nclass OrderService\n{\n    public function __construct(\n        private PaymentGateway $paymentGateway,\n        private InventoryService $inventoryService,\n        private NotificationService $notificationService,\n        private EventDispatcher $events\n    ) {}\n\n    public function createOrder(array $data): Order\n    {\n        \u002F\u002F Complex business logic\n        DB::beginTransaction();\n\n        try {\n            \u002F\u002F Validate inventory\n            $this->inventoryService->checkAvailability($data['items']);\n\n            \u002F\u002F Calculate pricing\n            $total = $this->calculateTotal($data['items'], $data['discount_code'] ?? null);\n\n            \u002F\u002F Create order\n            $order = Order::create([\n                'user_id' => auth()->id(),\n                'items' => $data['items'],\n                'total' => $total,\n                'status' => 'pending',\n            ]);\n\n            \u002F\u002F Process payment\n            $payment = $this->paymentGateway->charge([\n                'amount' => $total,\n                'payment_method' => $data['payment_method'],\n                'order_id' => $order->id,\n            ]);\n\n            \u002F\u002F Update order with payment info\n            $order->update([\n                'payment_id' => $payment->id,\n                'status' => 'paid',\n            ]);\n\n            \u002F\u002F Update inventory\n            $this->inventoryService->reserveItems($data['items']);\n\n            \u002F\u002F Send notifications\n            $this->notificationService->sendOrderConfirmation($order);\n\n            DB::commit();\n\n            \u002F\u002F Dispatch events\n            $this->events->dispatch(new OrderPlaced($order));\n\n            return $order;\n\n        } catch (\\Exception $e) {\n            DB::rollBack();\n            throw new OrderCreationException('Failed to create order', 0, $e);\n        }\n    }\n\n    private function calculateTotal(array $items, ?string $discountCode): float\n    {\n        \u002F\u002F Complex pricing logic\n        $subtotal = collect($items)->sum(fn($item) => $item['price'] * $item['quantity']);\n\n        if ($discountCode) {\n            $discount = $this->applyDiscount($discountCode, $subtotal);\n            return $subtotal - $discount;\n        }\n\n        return $subtotal;\n    }\n}\n```\n\n**Actions (Single Responsibility Pattern):**\nOne action = one specific task. Highly reusable and testable.\n\n```php\n\u002F\u002F Action - Does one thing well\nclass CreateUserAction\n{\n    public function __construct(\n        private HashService $hash,\n        private EventDispatcher $events\n    ) {}\n\n    public function execute(array $data): User\n    {\n        \u002F\u002F Validate business rules\n        if (User::where('email', $data['email'])->exists()) {\n            throw new UserAlreadyExistsException();\n        }\n\n        \u002F\u002F Create user\n        $user = User::create([\n            'name' => $data['name'],\n            'email' => $data['email'],\n            'password' => $this->hash->make($data['password']),\n        ]);\n\n        \u002F\u002F Dispatch event\n        $this->events->dispatch(new UserCreated($user));\n\n        return $user;\n    }\n}\n\n\u002F\u002F Another action - Single purpose\nclass SendWelcomeEmailAction\n{\n    public function __construct(private Mailer $mailer) {}\n\n    public function execute(User $user): void\n    {\n        $this->mailer->to($user->email)->send(new WelcomeEmail($user));\n    }\n}\n\n\u002F\u002F Using actions in service\nclass UserService\n{\n    public function __construct(\n        private CreateUserAction $createUser,\n        private SendWelcomeEmailAction $sendWelcome,\n        private AssignDefaultRoleAction $assignRole\n    ) {}\n\n    public function register(array $data): User\n    {\n        $user = $this->createUser->execute($data);\n        $this->assignRole->execute($user, 'user');\n        $this->sendWelcome->execute($user);\n\n        return $user;\n    }\n}\n```\n\n**Decision Guide:**\n\n| Use Case | Pattern | Example |\n|----------|---------|---------|\n| Simple CRUD with validation | Controller only | Updating user profile |\n| Single, reusable operation | Action | Sending email, creating user |\n| Complex business workflow | Service | Checkout process, invoice generation |\n| Multiple coordinated tasks | Service + Actions | Order processing with notifications |\n| Cross-cutting concerns | Middleware | Logging, authentication |\n| Data transformation | Resource\u002FTransformer | API response formatting |\n\n**Comparison Table:**\n\n| Aspect | Controller | Service | Action |\n|--------|-----------|---------|--------|\n| Responsibility | HTTP concerns | Business logic | Single task |\n| Reusability | Low (HTTP bound) | High | Very high |\n| Testability | Medium | High | Very high |\n| Complexity | Simple | Complex | Simple |\n| State | Request-scoped | Stateless | Stateless |\n| Dependencies | Request, validation | Multiple services | Focused dependencies |\n\n**When to Use Each:**\n\n```php\n\u002F\u002F 1. Simple CRUD - Controller is enough\nclass ProfileController extends Controller\n{\n    public function update(UpdateProfileRequest $request)\n    {\n        auth()->user()->update($request->validated());\n        return back()->with('success', 'Profile updated');\n    }\n}\n\n\u002F\u002F 2. Reusable operation - Use Action\nclass CalculateTaxAction\n{\n    public function execute(float $amount, string $country, array $items): float\n    {\n        \u002F\u002F Tax calculation logic used in multiple places\n        return $amount * 0.2;\n    }\n}\n\n\u002F\u002F 3. Complex workflow - Use Service\nclass SubscriptionService\n{\n    public function subscribe(User $user, Plan $plan, PaymentMethod $paymentMethod): Subscription\n    {\n        \u002F\u002F Complex logic: validate, charge, create subscription, send emails, update billing\n        DB::transaction(function () use ($user, $plan, $paymentMethod) {\n            $charge = $this->gateway->charge($paymentMethod, $plan->price);\n            $subscription = $user->subscriptions()->create([...]);\n            $this->billingService->createInvoice($subscription, $charge);\n            $this->notificationService->sendWelcome($user);\n            return $subscription;\n        });\n    }\n}\n\n\u002F\u002F 4. Controller with Service\nclass SubscriptionController extends Controller\n{\n    public function store(SubscribeRequest $request, SubscriptionService $service)\n    {\n        $subscription = $service->subscribe(\n            $request->user(),\n            $request->getPlan(),\n            $request->getPaymentMethod()\n        );\n\n        return new SubscriptionResource($subscription);\n    }\n}\n```\n\n**Best Practices:**\n\n1. **Start Simple**: Begin with controllers, refactor when complexity grows\n2. **Single Responsibility**: Each class should have one reason to change\n3. **Testability**: Actions are easiest to test, services need mocking\n4. **Reusability**: Actions can be composed into services\n5. **Domain Logic**: Put business rules in models or dedicated classes\n\n**Anti-Patterns to Avoid:**\n\n```php\n\u002F\u002F FAT CONTROLLER - AVOID\nclass OrderController extends Controller\n{\n    public function store(Request $request)\n    {\n        \u002F\u002F Validation\n        \u002F\u002F Inventory check\n        \u002F\u002F Price calculation\n        \u002F\u002F Payment processing\n        \u002F\u002F Email sending\n        \u002F\u002F Logging\n        \u002F\u002F Everything here - BAD!\n    }\n}\n\n\u002F\u002F GOD SERVICE - AVOID\nclass GodService\n{\n    \u002F\u002F Handles users, orders, payments, emails, everything\n}\n\n\u002F\u002F ACTION WITH SIDE EFFECTS - AVOID\nclass SendEmailAction\n{\n    public function execute(User $user)\n    {\n        $this->sendEmail($user);\n        $this->logEmail($user);\n        $this->updateLastEmailSent($user); \u002F\u002F Side effect!\n        $this->notifyAdmin($user); \u002F\u002F Another side effect!\n    }\n}\n```\n\n**Testing Examples:**\n\n```php\n\u002F\u002F Testing Action (Easy)\npublic function test_create_user_action()\n{\n    $action = new CreateUserAction(new HashService(), new EventDispatcher());\n    $user = $action->execute(['name' => 'John', 'email' => 'john@test.com', 'password' => 'pass']);\n\n    $this->assertDatabaseHas('users', ['email' => 'john@test.com']);\n}\n\n\u002F\u002F Testing Service (More complex)\npublic function test_order_service()\n{\n    $gateway = Mockery::mock(PaymentGateway::class);\n    $gateway->shouldReceive('charge')->once()->andReturn(new Payment());\n\n    $service = new OrderService($gateway, new InventoryService(), new NotificationService());\n    $order = $service->createOrder([...]);\n\n    $this->assertEquals('paid', $order->status);\n}\n```\n\n**Performance Considerations:**\n- Actions have minimal overhead\n- Services can be cached as singletons\n- Controllers are recreated per request\n- Use dependency injection for testability\n\n**Follow-up Questions:**\n- How do you decide when to create a service vs an action?\n- Can actions call other actions?\n- How do you handle transactions across multiple services?\n- What's your folder structure for actions and services?",[20,352,353,23,218],"Services","Actions",{"id":355,"category":356,"question":357,"answer":358,"level":343,"tags":359},23,"Repository Pattern","How do you implement Repository Pattern in Laravel?","The Repository Pattern abstracts data access logic from business logic, making code more testable and maintainable.\n\n**Repository Pattern Structure:**\n\n```php\n\u002F\u002F 1. Interface (Contract)\nnamespace App\\Contracts\\Repositories;\n\ninterface UserRepositoryInterface\n{\n    public function all(): Collection;\n    public function find(int $id): ?User;\n    public function findOrFail(int $id): User;\n    public function create(array $data): User;\n    public function update(int $id, array $data): bool;\n    public function delete(int $id): bool;\n    public function findByEmail(string $email): ?User;\n    public function getActiveUsers(): Collection;\n    public function paginate(int $perPage = 15);\n}\n\n\u002F\u002F 2. Implementation\nnamespace App\\Repositories;\n\nuse App\\Contracts\\Repositories\\UserRepositoryInterface;\nuse App\\Models\\User;\nuse Illuminate\\Database\\Eloquent\\Collection;\nuse Illuminate\\Pagination\\LengthAwarePaginator;\n\nclass EloquentUserRepository implements UserRepositoryInterface\n{\n    protected User $model;\n\n    public function __construct(User $model)\n    {\n        $this->model = $model;\n    }\n\n    public function all(): Collection\n    {\n        return $this->model->all();\n    }\n\n    public function find(int $id): ?User\n    {\n        return $this->model->find($id);\n    }\n\n    public function findOrFail(int $id): User\n    {\n        return $this->model->findOrFail($id);\n    }\n\n    public function create(array $data): User\n    {\n        return $this->model->create($data);\n    }\n\n    public function update(int $id, array $data): bool\n    {\n        $user = $this->findOrFail($id);\n        return $user->update($data);\n    }\n\n    public function delete(int $id): bool\n    {\n        $user = $this->findOrFail($id);\n        return $user->delete();\n    }\n\n    public function findByEmail(string $email): ?User\n    {\n        return $this->model->where('email', $email)->first();\n    }\n\n    public function getActiveUsers(): Collection\n    {\n        return $this->model->where('is_active', true)->get();\n    }\n\n    public function paginate(int $perPage = 15): LengthAwarePaginator\n    {\n        return $this->model->paginate($perPage);\n    }\n}\n\n\u002F\u002F 3. Alternative Implementation (Cache)\nnamespace App\\Repositories\\Cache;\n\nuse App\\Contracts\\Repositories\\UserRepositoryInterface;\nuse Illuminate\\Support\\Facades\\Cache;\n\nclass CachedUserRepository implements UserRepositoryInterface\n{\n    public function __construct(\n        private UserRepositoryInterface $repository,\n        private int $ttl = 3600\n    ) {}\n\n    public function find(int $id): ?User\n    {\n        return Cache::remember(\"user:{$id}\", $this->ttl, function () use ($id) {\n            return $this->repository->find($id);\n        });\n    }\n\n    public function create(array $data): User\n    {\n        $user = $this->repository->create($data);\n        Cache::forget(\"user:{$user->id}\");\n        return $user;\n    }\n\n    public function update(int $id, array $data): bool\n    {\n        $result = $this->repository->update($id, $data);\n        Cache::forget(\"user:{$id}\");\n        return $result;\n    }\n\n    \u002F\u002F Implement other methods...\n}\n\n\u002F\u002F 4. Base Repository (DRY)\nabstract class BaseRepository\n{\n    protected Model $model;\n\n    public function __construct(Model $model)\n    {\n        $this->model = $model;\n    }\n\n    public function all(): Collection\n    {\n        return $this->model->all();\n    }\n\n    public function find(int $id): ?Model\n    {\n        return $this->model->find($id);\n    }\n\n    public function findOrFail(int $id): Model\n    {\n        return $this->model->findOrFail($id);\n    }\n\n    public function create(array $data): Model\n    {\n        return $this->model->create($data);\n    }\n\n    public function update(int $id, array $data): bool\n    {\n        $model = $this->findOrFail($id);\n        return $model->update($data);\n    }\n\n    public function delete(int $id): bool\n    {\n        $model = $this->findOrFail($id);\n        return $model->delete();\n    }\n\n    public function paginate(int $perPage = 15): LengthAwarePaginator\n    {\n        return $this->model->paginate($perPage);\n    }\n\n    public function beginTransaction()\n    {\n        DB::beginTransaction();\n    }\n\n    public function commit()\n    {\n        DB::commit();\n    }\n\n    public function rollBack()\n    {\n        DB::rollBack();\n    }\n}\n\n\u002F\u002F Specific repository extending base\nclass PostRepository extends BaseRepository implements PostRepositoryInterface\n{\n    public function __construct(Post $model)\n    {\n        parent::__construct($model);\n    }\n\n    public function getPublishedPosts(): Collection\n    {\n        return $this->model->where('published_at', '\u003C=', now())->get();\n    }\n\n    public function getPostsByUser(int $userId): Collection\n    {\n        return $this->model->where('user_id', $userId)->get();\n    }\n}\n```\n\n**Service Provider Binding:**\n\n```php\nnamespace App\\Providers;\n\nuse App\\Contracts\\Repositories\\UserRepositoryInterface;\nuse App\\Repositories\\EloquentUserRepository;\nuse App\\Repositories\\Cache\\CachedUserRepository;\nuse Illuminate\\Support\\ServiceProvider;\n\nclass RepositoryServiceProvider extends ServiceProvider\n{\n    public function register(): void\n    {\n        \u002F\u002F Bind interface to implementation\n        $this->app->bind(UserRepositoryInterface::class, function ($app) {\n            $repository = new EloquentUserRepository(new User());\n\n            \u002F\u002F Wrap with cache for production\n            if ($app->environment('production')) {\n                $repository = new CachedUserRepository($repository);\n            }\n\n            return $repository;\n        });\n\n        \u002F\u002F Or simple binding\n        $this->app->bind(\n            UserRepositoryInterface::class,\n            EloquentUserRepository::class\n        );\n    }\n}\n```\n\n**Using Repository in Controllers:**\n\n```php\nclass UserController extends Controller\n{\n    public function __construct(\n        private UserRepositoryInterface $users\n    ) {}\n\n    public function index()\n    {\n        $users = $this->users->paginate(15);\n        return UserResource::collection($users);\n    }\n\n    public function show(int $id)\n    {\n        $user = $this->users->findOrFail($id);\n        return new UserResource($user);\n    }\n\n    public function store(StoreUserRequest $request)\n    {\n        $user = $this->users->create($request->validated());\n        return new UserResource($user);\n    }\n\n    public function update(UpdateUserRequest $request, int $id)\n    {\n        $this->users->update($id, $request->validated());\n        return response()->noContent();\n    }\n\n    public function destroy(int $id)\n    {\n        $this->users->delete($id);\n        return response()->noContent();\n    }\n}\n```\n\n**Advanced Repository Features:**\n\n```php\n\u002F\u002F Criteria pattern\ninterface Criteria\n{\n    public function apply(Builder $query): Builder;\n}\n\nclass ActiveUsersCriteria implements Criteria\n{\n    public function apply(Builder $query): Builder\n    {\n        return $query->where('is_active', true);\n    }\n}\n\nclass UserRepository extends BaseRepository\n{\n    protected array $criteria = [];\n\n    public function pushCriteria(Criteria $criteria): self\n    {\n        $this->criteria[] = $criteria;\n        return $this;\n    }\n\n    public function get(): Collection\n    {\n        $query = $this->model->newQuery();\n\n        foreach ($this->criteria as $criterion) {\n            $query = $criterion->apply($query);\n        }\n\n        return $query->get();\n    }\n}\n\n\u002F\u002F Usage\n$users = $this->users->pushCriteria(new ActiveUsersCriteria())->get();\n\n\u002F\u002F Specification pattern\nclass UserIsActiveSpecification\n{\n    public function isSatisfiedBy(User $user): bool\n    {\n        return $user->is_active === true;\n    }\n}\n\nclass UserRepository extends BaseRepository\n{\n    public function findBySpecification($specification): Collection\n    {\n        return $this->model->all()->filter(function ($user) use ($specification) {\n            return $specification->isSatisfiedBy($user);\n        });\n    }\n}\n```\n\n**Testing with Repositories:**\n\n```php\nclass UserControllerTest extends TestCase\n{\n    public function test_user_index()\n    {\n        \u002F\u002F Mock repository\n        $repository = Mockery::mock(UserRepositoryInterface::class);\n        $repository->shouldReceive('paginate')\n            ->once()\n            ->with(15)\n            ->andReturn(collect([\n                new User(['name' => 'John']),\n                new User(['name' => 'Jane']),\n            ]));\n\n        $this->app->instance(UserRepositoryInterface::class, $repository);\n\n        $response = $this->getJson('\u002Fapi\u002Fusers');\n        $response->assertStatus(200);\n    }\n}\n\n\u002F\u002F Using database for repository testing\npublic function test_repository_find()\n{\n    $user = User::factory()->create();\n    $repository = new EloquentUserRepository(new User());\n\n    $found = $repository->find($user->id);\n    $this->assertEquals($user->id, $found->id);\n}\n```\n\n**Pros and Cons:**\n\n**Pros:**\n- Easy to switch data sources\n- Centralized data access logic\n- Better testability with mocks\n- Clean separation of concerns\n- Cache implementation can be added without changing business logic\n\n**Cons:**\n- Additional complexity\n- More boilerplate code\n- May be overkill for simple CRUD\n- Learning curve for team\n\n**When to Use Repository Pattern:**\n- Large applications with complex data access\n- Multiple data sources (API, cache, database)\n- Need for extensive testing\n- Team working on different layers\n- Future-proofing for data source changes\n\n**When NOT to Use:**\n- Simple CRUD applications\n- Rapid prototyping\n- Small team projects\n- Direct Eloquent is sufficient\n\n**Best Practices:**\n- Keep repositories focused on data access only\n- Use interfaces for contracts\n- Don't put business logic in repositories\n- Use dependency injection\n- Implement caching at repository level\n- Use base repository for common methods\n\n**Common Mistakes:**\n- Putting business logic in repositories\n- Not using interfaces\n- Over-engineering for simple needs\n- Leaking Eloquent specifics through interface\n- Not handling transactions properly\n\n**Performance Considerations:**\n- Repository adds minimal overhead\n- Cache implementation can improve performance\n- Batch operations should be optimized\n- Consider read\u002Fwrite splitting at repository level\n\n**Follow-up Questions:**\n- How do you handle complex relationships with repositories?\n- How do you test repositories that use caching?\n- Can repositories handle different database connections?\n- How do you implement soft deletes in repositories?",[356,218,20,360],"Data Access",{"id":362,"category":363,"question":364,"answer":365,"level":343,"tags":366},24,"Eloquent Relationships","How do you optimize Eloquent queries and avoid N+1 problem?","Optimizing Eloquent queries is crucial for application performance, especially with complex relationships.\n\n**The N+1 Problem:**\n\n```php\n\u002F\u002F Problem: N+1 queries\n$posts = Post::all(); \u002F\u002F 1 query\n\nforeach ($posts as $post) {\n    echo $post->user->name; \u002F\u002F N queries (one per post)\n}\n\u002F\u002F Total: 1 + N queries = Performance disaster!\n\n\u002F\u002F Solution: Eager Loading\n$posts = Post::with('user')->get(); \u002F\u002F 2 queries total\n\nforeach ($posts as $post) {\n    echo $post->user->name; \u002F\u002F No additional queries\n}\n```\n\n**Eager Loading Strategies:**\n\n```php\n\u002F\u002F Basic eager loading\n$users = User::with('posts')->get();\n\n\u002F\u002F Nested relationships\n$users = User::with('posts.comments')->get();\n\n\u002F\u002F Multiple relationships\n$users = User::with(['posts', 'profile', 'settings'])->get();\n\n\u002F\u002F Constrained eager loading\n$users = User::with(['posts' => function ($query) {\n    $query->where('is_published', true)\n          ->orderBy('created_at', 'desc')\n          ->limit(5);\n}])->get();\n\n\u002F\u002F Lazy eager loading (after retrieval)\n$users = User::all();\nif ($someCondition) {\n    $users->load('posts');\n}\n$users->loadMissing('profile'); \u002F\u002F Only loads if not already loaded\n\n\u002F\u002F Nested lazy loading\n$users->load(['posts.comments']);\n\n\u002F\u002F Dynamic eager loading\n$posts = Post::with($request->get('includes', []))->get();\n```\n\n**Advanced Optimization Techniques:**\n\n```php\n\u002F\u002F 1. Select specific columns\n$users = User::with('posts:id,title,user_id')\n    ->select('id', 'name', 'email')\n    ->get();\n\n\u002F\u002F 2. Aggregating related data (no extra queries)\n$users = User::withCount('posts')->get();\nforeach ($users as $user) {\n    echo $user->posts_count; \u002F\u002F Already calculated\n}\n\n\u002F\u002F Multiple counts\n$users = User::withCount(['posts', 'comments', 'likes'])->get();\n\n\u002F\u002F Conditional counts\n$users = User::withCount([\n    'posts' => function ($query) {\n        $query->where('is_published', true);\n    }\n])->get();\n\n\u002F\u002F 3. Aggregating values\n$users = User::withMax('posts', 'created_at')->get();\n\u002F\u002F $user->posts_max_created_at\n\n$users = User::withSum('orders', 'total')->get();\n\u002F\u002F $user->orders_sum_total\n\n$users = User::withAvg('ratings', 'score')->get();\n\u002F\u002F $user->ratings_avg_score\n\n\u002F\u002F 4. Existence checking (no eager loading needed)\n$users = User::has('posts')->get();\n$users = User::whereHas('posts', function ($query) {\n    $query->where('is_published', true);\n})->get();\n\n\u002F\u002F 5. Nested existence\n$users = User::whereHas('posts.comments', function ($query) {\n    $query->where('is_approved', true);\n})->get();\n\n\u002F\u002F 6. Subquery optimization\n$users = User::addSelect(['last_post_title' => Post::select('title')\n    ->whereColumn('user_id', 'users.id')\n    ->latest()\n    ->limit(1)\n])->get();\n\n\u002F\u002F 7. Subquery in where clause\n$users = User::where('created_at', '\u003C', function ($query) {\n    $query->select(DB::raw('MAX(created_at)'))\n          ->from('posts')\n          ->whereColumn('user_id', 'users.id');\n})->get();\n```\n\n**Chunking for Memory Efficiency:**\n\n```php\n\u002F\u002F Chunking (good for large datasets)\nUser::chunk(100, function ($users) {\n    foreach ($users as $user) {\n        \u002F\u002F Process user\n    }\n});\n\n\u002F\u002F Chunk with eager loading\nUser::with('posts')->chunk(50, function ($users) {\n    foreach ($users as $user) {\n        $user->posts->each(function ($post) {\n            \u002F\u002F Process post\n        });\n    }\n});\n\n\u002F\u002F Cursor (even more memory efficient)\nforeach (User::cursor() as $user) {\n    \u002F\u002F Process user one at a time\n}\n\n\u002F\u002F Chunk by ID for consistency\nUser::where('id', '>', $lastId)\n    ->orderBy('id')\n    ->chunk(100, function ($users) use (&$lastId) {\n        foreach ($users as $user) {\n            \u002F\u002F Process\n        }\n        $lastId = $users->last()->id;\n    });\n```\n\n**Query Optimization Techniques:**\n\n```php\n\u002F\u002F 1. Use indexes\nSchema::table('posts', function ($table) {\n    $table->index('user_id');\n    $table->index(['user_id', 'created_at']);\n    $table->index('published_at');\n});\n\n\u002F\u002F 2. Avoid N+1 in views\n\u002F\u002F Bad: @foreach($posts as $post) {{ $post->user->name }} @endforeach\n\u002F\u002F Good: $posts = Post::with('user')->get()\n\n\u002F\u002F 3. Use pluck for single column\n$names = User::pluck('name'); \u002F\u002F Faster than get()\n\n\u002F\u002F 4. Use lists for key-value pairs\n$users = User::pluck('name', 'id'); \u002F\u002F [1 => 'John', 2 => 'Jane']\n\n\u002F\u002F 5. Use chunk when processing\nUser::where('is_active', true)->chunk(500, function ($users) {\n    foreach ($users as $user) {\n        $user->update(['last_processed_at' => now()]);\n    }\n});\n\n\u002F\u002F 6. Batch updates\nUser::where('role', 'user')->update(['is_active' => false]);\n\n\u002F\u002F 7. Use raw expressions for complex operations\nUser::select(DB::raw('COUNT(*) as user_count, role'))\n    ->groupBy('role')\n    ->get();\n```\n\n**Caching Strategies:**\n\n```php\n\u002F\u002F Cache query results\n$users = Cache::remember('active_users', 3600, function () {\n    return User::with('posts')->where('is_active', true)->get();\n});\n\n\u002F\u002F Cache with tags (Redis)\n$users = Cache::tags(['users'])->remember('page_1', 3600, function () {\n    return User::paginate(15);\n});\n\n\u002F\u002F Invalidate cache on update\nUser::created(function ($user) {\n    Cache::tags(['users'])->flush();\n});\n\n\u002F\u002F Cache heavy queries\n$stats = Cache::remember('user_stats', 3600, function () {\n    return [\n        'total' => User::count(),\n        'active' => User::where('is_active', true)->count(),\n        'new_today' => User::whereDate('created_at', today())->count(),\n    ];\n});\n```\n\n**Monitoring and Debugging:**\n\n```php\n\u002F\u002F Enable query log\nDB::enableQueryLog();\n$users = User::with('posts')->get();\ndd(DB::getQueryLog());\n\n\u002F\u002F Clockwork or Laravel Debugbar\ncomposer require barryvdh\u002Flaravel-debugbar --dev\n\n\u002F\u002F Listen for queries\nDB::listen(function ($query) {\n    if ($query->time > 100) { \u002F\u002F Slow query > 100ms\n        Log::warning('Slow query detected', [\n            'sql' => $query->sql,\n            'bindings' => $query->bindings,\n            'time' => $query->time\n        ]);\n    }\n});\n\n\u002F\u002F Model profiling\nclass Post extends Model\n{\n    protected static function booted()\n    {\n        static::retrieved(function ($post) {\n            Log::debug('Post retrieved: ' . $post->id);\n        });\n    }\n}\n```\n\n**Best Practices Summary:**\n\n| Practice | When to Use |\n|----------|-------------|\n| Eager Loading (`with()`) | When you know you'll need relationships |\n| Lazy Eager Loading (`load()`) | Conditional relationship loading |\n| `withCount()` | When you only need counts, not models |\n| Chunking | Processing large datasets |\n| Cursor | Extremely large datasets with memory limits |\n| Caching | Expensive, infrequently changing queries |\n| Select Specific Columns | When you don't need all fields |\n\n**Common Performance Pitfalls:**\n\n```php\n\u002F\u002F 1. N+1 in loops\nforeach ($users as $user) {\n    $posts = $user->posts; \u002F\u002F N queries\n}\n\n\u002F\u002F 2. Loading entire tables\n$users = User::all(); \u002F\u002F Avoid on large tables\n\n\u002F\u002F 3. Unnecessary eager loading\n$posts = Post::with(['user', 'comments', 'tags', 'categories'])->get();\n\u002F\u002F Only load what you need\n\n\u002F\u002F 4. No indexes on foreign keys\n\u002F\u002F Always index foreign key columns\n\n\u002F\u002F 5. Using where on non-indexed columns\n\u002F\u002F Add indexes for frequently searched columns\n\n\u002F\u002F 6. Not using chunk for updates\nUser::all()->each->update(['processed' => true]); \u002F\u002F Memory heavy\nUser::chunk(100)->each->update(['processed' => true]); \u002F\u002F Better\n```\n\n**Real-World Example:**\n\n```php\n\u002F\u002F Dashboard query optimization\nclass DashboardController\n{\n    public function index()\n    {\n        \u002F\u002F Optimized query with eager loading, counts, and aggregates\n        $users = User::with(['posts' => function ($query) {\n                $query->latest()->limit(5);\n            }])\n            ->withCount(['posts', 'comments', 'likes'])\n            ->withSum('orders', 'total')\n            ->withAvg('ratings', 'score')\n            ->where('is_active', true)\n            ->orderBy('last_login_at', 'desc')\n            ->paginate(20);\n\n        \u002F\u002F Additional aggregated data (cached)\n        $stats = Cache::remember('dashboard_stats', 300, function () {\n            return [\n                'total_users' => User::count(),\n                'posts_today' => Post::whereDate('created_at', today())->count(),\n                'revenue_today' => Order::whereDate('created_at', today())->sum('total'),\n            ];\n        });\n\n        return view('dashboard', compact('users', 'stats'));\n    }\n}\n```\n\n**Follow-up Questions:**\n- How do you identify N+1 queries in production?\n- What's the difference between `load()` and `with()`?\n- How do you handle circular relationships in eager loading?\n- When should you use `chunk()` vs `cursor()`?",[62,243,367,368],"N+1","Optimization",{"id":370,"category":371,"question":372,"answer":373,"level":343,"tags":374},25,"Transactions & Deadlocks","How do you handle database transactions and prevent deadlocks?","Transactions ensure data integrity by grouping multiple database operations into a single atomic unit.\n\n**Basic Transactions:**\n\n```php\nuse Illuminate\\Support\\Facades\\DB;\n\n\u002F\u002F Automatic transaction\ndb::transaction(function () {\n    $user = User::create([...]);\n    $profile = Profile::create(['user_id' => $user->id, ...]);\n    $user->assignRole('user');\n});\n\n\u002F\u002F Manual transaction\ndb::beginTransaction();\n\ntry {\n    $user = User::create([...]);\n    $profile = Profile::create(['user_id' => $user->id, ...]);\n\n    db::commit();\n} catch (\\Exception $e) {\n    db::rollBack();\n    throw $e;\n}\n```\n\n**Model Events with Transactions:**\n\n```php\nclass OrderService\n{\n    public function createOrder(array $data): Order\n    {\n        return DB::transaction(function () use ($data) {\n            \u002F\u002F Lock user record for update\n            $user = User::lockForUpdate()->findOrFail($data['user_id']);\n\n            \u002F\u002F Validate stock\n            $this->checkInventory($data['items']);\n\n            \u002F\u002F Create order\n            $order = Order::create([\n                'user_id' => $user->id,\n                'total' => $this->calculateTotal($data['items']),\n                'status' => 'pending',\n            ]);\n\n            \u002F\u002F Create order items\n            foreach ($data['items'] as $item) {\n                $order->items()->create($item);\n                \u002F\u002F Update inventory\n                Product::where('id', $item['product_id'])\n                    ->decrement('stock', $item['quantity']);\n            }\n\n            \u002F\u002F Process payment\n            $payment = $this->processPayment($order, $data['payment_method']);\n            $order->update(['payment_id' => $payment->id, 'status' => 'paid']);\n\n            return $order;\n        });\n    }\n}\n```\n\n**Transaction Isolation Levels:**\n\n```php\n\u002F\u002F Set isolation level\ndb::statement('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');\n\nDB::transaction(function () {\n    \u002F\u002F SERIALIZABLE isolation\n}, 3); \u002F\u002F 3 retry attempts for deadlock\n\n\u002F\u002F Different isolation levels\n\u002F\u002F READ UNCOMMITTED - Dirty reads possible (fastest)\n\u002F\u002F READ COMMITTED - Default in many DBs\n\u002F\u002F REPEATABLE READ - MySQL default\n\u002F\u002F SERIALIZABLE - Highest isolation (slowest)\n```\n\n**Preventing Deadlocks:**\n\n```php\n\u002F\u002F 1. Consistent locking order\n\u002F\u002F Always lock in same order to prevent deadlocks\nclass TransferService\n{\n    public function transfer(Account $from, Account $to, float $amount)\n    {\n        \u002F\u002F Lock accounts in consistent order (by ID)\n        $accounts = collect([$from, $to])->sortBy('id');\n\n        DB::transaction(function () use ($accounts, $from, $to, $amount) {\n            \u002F\u002F Lock in sorted order\n            foreach ($accounts as $account) {\n                Account::where('id', $account->id)->lockForUpdate()->first();\n            }\n\n            $from->decrement('balance', $amount);\n            $to->increment('balance', $amount);\n        });\n    }\n}\n\n\u002F\u002F 2. Use shorter transactions\ndb::transaction(function () {\n    \u002F\u002F Only the critical operations\n    $criticalUpdate = User::where('id', $userId)->update(['balance' => $newBalance]);\n});\n\n\u002F\u002F 3. Retry on deadlock\ndb::transaction(function () {\n    \u002F\u002F Operations that might deadlock\n}, 5); \u002F\u002F Retry 5 times\n\n\u002F\u002F 4. Custom deadlock handling\ntry {\n    DB::transaction(function () {\n        \u002F\u002F Your queries\n    });\n} catch (\\Illuminate\\Database\\QueryException $e) {\n    if ($e->getCode() === '40001') { \u002F\u002F Deadlock error code\n        \u002F\u002F Retry logic\n        Log::warning('Deadlock detected, retrying...');\n        return $this->retryOperation();\n    }\n    throw $e;\n}\n```\n\n**Optimistic vs Pessimistic Locking:**\n\n```php\n\u002F\u002F Pessimistic Locking (LOCK FOR UPDATE)\ndb::transaction(function () {\n    $product = Product::lockForUpdate()->find($productId);\n    \u002F\u002F Other transactions cannot modify until commit\n    $product->decrement('stock', $quantity);\n});\n\n\u002F\u002F Optimistic Locking (using version column)\nclass Product extends Model\n{\n    public function updateStock($quantity)\n    {\n        $updated = DB::table('products')\n            ->where('id', $this->id)\n            ->where('version', $this->version)\n            ->update([\n                'stock' => DB::raw(\"stock - {$quantity}\"),\n                'version' => DB::raw(\"version + 1\")\n            ]);\n\n        if (!$updated) {\n            throw new OptimisticLockException('Product was modified by another user');\n        }\n    }\n}\n\n\u002F\u002F Using timestamp for optimistic locking\n$updated = DB::table('products')\n    ->where('id', $productId)\n    ->where('updated_at', $lastKnownTimestamp)\n    ->update([\n        'stock' => $newStock,\n        'updated_at' => now()\n    ]);\n```\n\n**Complex Transaction Patterns:**\n\n```php\n\u002F\u002F Nested transactions (savepoints)\ndb::transaction(function () {\n    $user = User::create([...]);\n\n    DB::transaction(function () use ($user) {\n        \u002F\u002F Nested - creates savepoint\n        $profile = Profile::create(['user_id' => $user->id]);\n\n        if ($someCondition) {\n            DB::rollBack(); \u002F\u002F Rolls back to savepoint only\n        }\n    });\n\n    \u002F\u002F Outer transaction still active\n});\n\n\u002F\u002F Transaction with model events disabled\nDB::transaction(function () {\n    User::withoutEvents(function () {\n        User::create([...]); \u002F\u002F No events fired\n    });\n});\n\n\u002F\u002F Cross-database transactions\nDB::transaction(function () {\n    DB::connection('mysql')->table('users')->insert([...]);\n    DB::connection('pgsql')->table('logs')->insert([...]);\n\n    if ($someCondition) {\n        DB::connection('mysql')->rollBack();\n        DB::connection('pgsql')->rollBack();\n    }\n});\n```\n\n**Testing Transactions:**\n\n```php\nclass OrderServiceTest extends TestCase\n{\n    use DatabaseTransactions; \u002F\u002F Automatically rolls back\n\n    public function test_order_creation_rolls_back_on_failure()\n    {\n        $this->expectException(\\Exception::class);\n\n        DB::shouldReceive('beginTransaction')->once();\n        DB::shouldReceive('rollBack')->once();\n\n        $service = new OrderService();\n        $service->createOrder(['invalid' => 'data']);\n    }\n}\n```\n\n**Best Practices:**\n\n1. **Keep transactions short** - Long transactions increase deadlock risk\n2. **Access tables in same order** - Prevents circular dependencies\n3. **Use appropriate isolation levels** - Higher isolation = more deadlocks\n4. **Implement retry logic** - Deadlocks are sometimes unavoidable\n5. **Monitor deadlock logs** - Identify problematic patterns\n6. **Avoid user input inside transactions** - Don't wait for user interaction\n7. **Don't mix storage engines** - MyISAM doesn't support transactions\n\n**Common Deadlock Scenarios:**\n\n```php\n\u002F\u002F SCENARIO 1: Circular dependency\n\u002F\u002F Transaction A: UPDATE users WHERE id=1; UPDATE profiles WHERE user_id=2;\n\u002F\u002F Transaction B: UPDATE profiles WHERE user_id=2; UPDATE users WHERE id=1;\n\u002F\u002F Solution: Always lock in same order\n\n\u002F\u002F SCENARIO 2: Range locks\nDB::transaction(function () {\n    \u002F\u002F Locks gap between IDs\n    $users = User::whereBetween('id', [1, 100])->lockForUpdate()->get();\n    \u002F\u002F Another transaction trying to insert id=50 will deadlock\n});\n\u002F\u002F Solution: Use smaller ranges or row-level locks\n\n\u002F\u002F SCENARIO 3: Missing indexes\nDB::transaction(function () {\n    \u002F\u002F No index on email - table scan, locks many rows\n    $user = User::where('email', 'user@example.com')->lockForUpdate()->first();\n});\n\u002F\u002F Solution: Always index columns used in WHERE clauses with locking\n```\n\n**Monitoring Tools:**\n\n```sql\n-- MySQL: Show current transactions\nSHOW ENGINE INNODB STATUS;\nSELECT * FROM information_schema.INNODB_TRX;\n\n-- PostgreSQL\nSELECT * FROM pg_locks;\nSELECT * FROM pg_stat_activity WHERE state = 'active';\n\n-- Log slow transactions\nDB::listen(function ($query) {\n    if ($query->time > 1000 && DB::transactionLevel() > 0) {\n        Log::warning('Slow query in transaction', [\n            'sql' => $query->sql,\n            'time' => $query->time\n        ]);\n    }\n});\n```\n\n**Real-World Example:**\n\n```php\nclass BookingService\n{\n    public function bookTicket(int $eventId, int $seatId, int $userId): Booking\n    {\n        $maxRetries = 3;\n\n        for ($attempt = 1; $attempt \u003C= $maxRetries; $attempt++) {\n            try {\n                return DB::transaction(function () use ($eventId, $seatId, $userId) {\n                    \u002F\u002F Lock seat with timeout\n                    $seat = Seat::where('event_id', $eventId)\n                        ->where('id', $seatId)\n                        ->lockForUpdate()\n                        ->first();\n\n                    if (!$seat || $seat->is_booked) {\n                        throw new SeatNotAvailableException();\n                    }\n\n                    \u002F\u002F Create booking\n                    $booking = Booking::create([\n                        'user_id' => $userId,\n                        'seat_id' => $seatId,\n                        'event_id' => $eventId,\n                        'booked_at' => now(),\n                    ]);\n\n                    \u002F\u002F Mark seat as booked\n                    $seat->update(['is_booked' => true, 'booking_id' => $booking->id]);\n\n                    \u002F\u002F Release any temporary holds\n                    TempHold::where('seat_id', $seatId)->delete();\n\n                    return $booking;\n                });\n            } catch (\\Illuminate\\Database\\QueryException $e) {\n                if ($e->getCode() === '40001' && $attempt \u003C $maxRetries) {\n                    \u002F\u002F Deadlock detected, retry\n                    usleep(100000 * $attempt); \u002F\u002F Exponential backoff\n                    continue;\n                }\n                throw $e;\n            }\n        }\n\n        throw new BookingException('Unable to book ticket after ' . $maxRetries . ' attempts');\n    }\n}\n```\n\n**Follow-up Questions:**\n- What's the difference between optimistic and pessimistic locking?\n- How do you handle long-running transactions?\n- What are the performance implications of different isolation levels?\n- How do you test for deadlocks?",[375,376,54,377],"Transactions","Deadlocks","Concurrency",{"id":379,"category":380,"question":381,"answer":382,"level":343,"tags":383},49,"Advanced","How do you optimize Laravel for high-traffic applications?","High-traffic Laravel optimization involves multiple layers: caching, queues, database, and infrastructure.\n\n**1. Configuration Caching:**\n\n```bash\n# Cache all configurations\nphp artisan config:cache\nphp artisan route:cache\nphp artisan view:cache\nphp artisan event:cache\n\n# For deployment\nphp artisan optimize\n```\n\n**2. Queue Optimization:**\n\n```php\n\u002F\u002F Use Redis for queue\nQUEUE_CONNECTION=redis\n\n\u002F\u002F Multiple workers with supervisor\n[program:laravel-worker]\nprocess_name=%(program_name)s_%(process_num)02d\ncommand=php \u002Fvar\u002Fwww\u002Fartisan queue:work redis --sleep=3 --tries=3 --max-time=3600\nnumprocs=8\n\n\u002F\u002F Use different queues for priorities\nProcessPodcast::dispatch()->onQueue('high');\nMail::queue()->onQueue('low');\n```\n\n**3. Database Optimization:**\n\n```php\n\u002F\u002F Use read\u002Fwrite connections\n'mysql' => [\n    'read' => [\n        'host' => ['192.168.1.1', '192.168.1.2'], \u002F\u002F Read replicas\n    ],\n    'write' => [\n        'host' => '192.168.1.3', \u002F\u002F Write master\n    ],\n    'sticky' => true,\n],\n\n\u002F\u002F Index frequently queried columns\nSchema::table('users', function ($table) {\n    $table->index('email');\n    $table->index(['role', 'created_at']);\n});\n\n\u002F\u002F Use chunking for large datasets\nUser::chunk(1000, function ($users) {\n    foreach ($users as $user) {\n        \u002F\u002F Process\n    }\n});\n```\n\n**4. Caching Strategy:**\n\n```php\n\u002F\u002F Cache expensive queries\nclass UserRepository\n{\n    public function getActiveUsers()\n    {\n        return Cache::remember('active_users', 3600, function () {\n            return User::where('is_active', true)->get();\n        });\n    }\n}\n\n\u002F\u002F Cache response\nRoute::middleware('cache.headers:public;max_age=3600;etag')->get('\u002Fapi\u002Fusers', function () {\n    return User::all();\n});\n\n\u002F\u002F Use Redis for caching\nCACHE_DRIVER=redis\n```\n\n**5. Octane for High Performance:**\n\n```bash\ncomposer require laravel\u002Foctane\nphp artisan octane:install --server=swoole\nphp artisan octane:start --workers=8 --task-workers=16 --port=8000\n```\n\n```php\n\u002F\u002F Octane configuration\n\u002F\u002F config\u002Foctane.php\n'workers' => 8,\n'task_workers' => 16,\n'max_requests' => 1000,\n'watch' => [\n    'app', 'bootstrap', 'config', 'database', 'routes',\n],\n```\n\n**6. CDN and Asset Optimization:**\n\n```php\n\u002F\u002F Mix versioning\nmix.js('resources\u002Fjs\u002Fapp.js', 'public\u002Fjs')\n   .version();\n\n\u002F\u002F Use CDN for assets\nASSET_URL=https:\u002F\u002Fcdn.example.com\n\n\u002F\u002F Lazy load images\n\u003Cimg loading=\"lazy\" src=\"image.jpg\">\n```\n\n**7. Eloquent Optimization:**\n\n```php\n\u002F\u002F Eager load to prevent N+1\n$posts = Post::with('user', 'comments')->get();\n\n\u002F\u002F Select only needed columns\n$users = User::select('id', 'name', 'email')->get();\n\n\u002F\u002F Use chunk\u002Fcursor for large datasets\nforeach (User::cursor() as $user) {\n    \u002F\u002F Process\n}\n```\n\n**8. Session Optimization:**\n\n```php\n\u002F\u002F Use Redis for sessions\nSESSION_DRIVER=redis\n\n\u002F\u002F Or database for multi-server\nSESSION_DRIVER=database\nphp artisan session:table\n```\n\n**9. HTTP\u002F2 and Compression:**\n\n```apache\n# .htaccess or nginx config\n# Enable compression\nAddOutputFilterByType DEFLATE text\u002Fhtml text\u002Fcss text\u002Fjavascript\n\n# Enable keep-alive\nHeader set Connection keep-alive\n```\n\n**10. Monitoring Tools:**\n\n```php\n\u002F\u002F Laravel Telescope for debugging\ncomposer require laravel\u002Ftelescope\n\n\u002F\u002F Laravel Horizon for queue monitoring\ncomposer require laravel\u002Fhorizon\n\n\u002F\u002F Laravel Pulse for performance monitoring\ncomposer require laravel\u002Fpulse\n```\n\n**11. Load Balancing:**\n\n```php\n\u002F\u002F Ensure sessions are shared\nSESSION_DOMAIN=.example.com\n\n\u002F\u002F Use Redis for cache and sessions\n\u002F\u002F Use shared storage for uploads (S3)\n```\n\n**12. Code Optimization:**\n\n```php\n\u002F\u002F Avoid N+1 queries\n\u002F\u002F Use cached queries\n\u002F\u002F Lazy load relationships when needed\n\u002F\u002F Use database transactions for bulk operations\n```\n\n**Benchmarking:**\n\n```bash\n# Use Apache Bench\nab -n 1000 -c 100 https:\u002F\u002Fexample.com\u002F\n\n# Use Laravel's built-in\nphp artisan optimize\n```\n\n**Common Bottlenecks:**\n- Database queries (use EXPLAIN)\n- File operations (use cloud storage)\n- Blocking I\u002FO (use queues)\n- Session locking (use Redis)\n\n**Deployment Checklist:**\n```bash\n# Production deployment\ncomposer install --optimize-autoloader --no-dev\nphp artisan config:cache\nphp artisan route:cache\nphp artisan view:cache\nphp artisan event:cache\nphp artisan optimize\n```\n\n**Best Practices Summary:**\n- Cache everything that can be cached\n- Queue everything that can be delayed\n- Use read replicas for reporting\n- Implement CDN for static assets\n- Monitor and profile regularly\n- Scale horizontally when needed\n\n**Follow-up Questions:**\n- How do you identify performance bottlenecks?\n- What's the maximum requests per second you've achieved?\n- How do you handle database connection pooling?",[243,368,384,385],"High Traffic","Scaling",{"id":387,"category":380,"question":388,"answer":389,"level":343,"tags":390},50,"How does Laravel Octane work and when should you use it?","Octane supercharges Laravel by running the application in memory using Swoole or RoadRunner, eliminating framework bootstrap overhead per request.\n\n**How Octane Works:**\n\n```bash\n# Traditional PHP: Bootstrap on every request\nRequest → PHP Process → Bootstrap → Handle → Response → Kill Process\n\n# Octane: Bootstrap once, handle many requests\nStart Server → Bootstrap → Request → Handle → Response → Request → Handle → Response\n```\n\n**Installation:**\n\n```bash\ncomposer require laravel\u002Foctane\nphp artisan octane:install --server=swoole\n```\n\n**Basic Configuration:**\n\n```php\n\u002F\u002F config\u002Foctane.php\nreturn [\n    'server' => 'swoole',\n    'workers' => 8, \u002F\u002F CPU cores * 2\n    'task_workers' => 16, \u002F\u002F For async tasks\n    'max_requests' => 1000, \u002F\u002F Restart workers after N requests\n    'watch' => [\n        'app', 'bootstrap', 'config', 'database', 'routes',\n    ],\n];\n```\n\n**Running Octane:**\n\n```bash\n# Start server\nphp artisan octane:start --port=8000\n\n# With specific workers\nphp artisan octane:start --workers=4 --task-workers=8\n\n# In production\nphp artisan octane:start --server=swoole --host=0.0.0.0 --port=8000 --workers=32\n\n# Stop server\nphp artisan octane:stop\n\n# Reload workers after code change\nphp artisan octane:reload\n```\n\n**Memory Management:**\n\n```php\n\u002F\u002F Octane services persist between requests\n\u002F\u002F Use singleton bindings carefully\n\n\u002F\u002F Good: Stateless services\n$this->app->singleton(PaymentGateway::class, function ($app) {\n    return new PaymentGateway();\n});\n\n\u002F\u002F Bad: Stateful services (resets each request)\n$this->app->scoped(Request::class, function ($app) {\n    return Request::capture(); \u002F\u002F New instance per request\n});\n\n\u002F\u002F Prevent memory leaks\nclass UserController\n{\n    public function index()\n    {\n        \u002F\u002F Avoid static properties\n        static $cache = []; \u002F\u002F Will grow over time\n        \n        \u002F\u002F Instead use\n        Cache::remember('users', 3600, function () {\n            return User::all();\n        });\n    }\n}\n```\n\n**Task Workers (Async Processing):**\n\n```php\nclass OrderController\n{\n    public function store(Request $request)\n    {\n        $order = Order::create($request->validated());\n        \n        \u002F\u002F Run async task without blocking\n        Octane::task(function () use ($order) {\n            Mail::to($order->user)->send(new OrderConfirmation($order));\n        });\n        \n        return response()->json($order, 201);\n    }\n}\n\n\u002F\u002F With task result\n$result = Octane::task(function () {\n    return DB::table('users')->count();\n});\n```\n\n**WebSocket Support:**\n\n```php\n\u002F\u002F config\u002Foctane.php\n'websocket' => [\n    'enabled' => true,\n    'port' => 6001,\n],\n\n\u002F\u002F Broadcast events\nclass OrderUpdated implements ShouldBroadcast\n{\n    public function broadcastOn()\n    {\n        return new Channel('orders');\n    }\n}\n```\n\n**Request Lifecycle Differences:**\n\n```php\n\u002F\u002F Traditional: Service providers run per request\n\u002F\u002F Octane: Service providers run once at boot\n\n\u002F\u002F Deferred providers are not recommended in Octane\nclass HeavyServiceProvider extends ServiceProvider implements DeferrableProvider\n{\n    \u002F\u002F Avoid - deferred providers may cause issues\n}\n\n\u002F\u002F Instead register early\npublic function register()\n{\n    $this->app->singleton(HeavyService::class);\n}\n```\n\n**Testing Octane Compatibility:**\n\n```bash\nphp artisan octane:check\n```\n\n**Common Issues to Fix:**\n\n```php\n\u002F\u002F 1. Avoid static properties\nclass BadClass\n{\n    private static $counter = 0; \u002F\u002F Will persist across requests\n}\n\n\u002F\u002F 2. Use fresh database connections\nDB::purge(); \u002F\u002F On worker restart\n\n\u002F\u002F 3. Reset service states\napp()->forgetInstance(SomeService::class);\n\n\u002F\u002F 4. Close connections\nEvent::listen(RequestHandled::class, function () {\n    DB::disconnect();\n});\n```\n\n**Performance Benchmarks:**\n\n| Framework | Requests\u002FSecond | Memory\u002FRequest |\n|-----------|----------------|----------------|\n| PHP-FPM | ~200-300 | ~2-3 MB |\n| Octane (Swoole) | ~2000-3000 | ~0.1 MB |\n| RoadRunner | ~1500-2500 | ~0.15 MB |\n\n**When to Use Octane:**\n- High-traffic APIs (1000+ req\u002Fsec)\n- Real-time applications (WebSockets)\n- Microservices architecture\n- Serverless environments (with warm workers)\n\n**When NOT to Use Octane:**\n- Shared hosting (no Swoole extension)\n- Legacy code with static state\n- Applications with memory leaks\n- Simple CRUD apps (\u003C 100 req\u002Fsec)\n\n**Best Practices:**\n- Use `scoped` bindings for request-specific data\n- Monitor memory usage over time\n- Set `max_requests` to restart workers periodically\n- Use `octane:reload` after deployments\n- Test thoroughly for state leakage\n\n**Monitoring:**\n\n```bash\n# Check octane status\nphp artisan octane:status\n\n# Monitor metrics\nphp artisan octane:metrics\n\n# Log worker restarts\nOctane::onWorkerRestart(function () {\n    Log::info('Worker restarted');\n});\n```\n\n**Follow-up Questions:**\n- How do you handle database connections in Octane?\n- What's the difference between Swoole and RoadRunner?\n- How do you debug memory leaks in Octane?",[391,243,392,393],"Octane","Swoole","RoadRunner",{"id":395,"category":380,"question":396,"answer":397,"level":343,"tags":398},51,"How do you implement event sourcing in Laravel?","Event sourcing stores state changes as a sequence of events, allowing you to rebuild state by replaying events.\n\n**Basic Event Sourcing Structure:**\n\n```php\n\u002F\u002F Domain Events\nclass MoneyAdded\n{\n    public function __construct(\n        public string $accountId,\n        public float $amount,\n        public string $currency,\n        public DateTimeImmutable $occurredAt\n    ) {}\n}\n\nclass MoneySubtracted\n{\n    public function __construct(\n        public string $accountId,\n        public float $amount,\n        public string $currency,\n        public DateTimeImmutable $occurredAt\n    ) {}\n}\n\n\u002F\u002F Aggregate Root\nclass BankAccount\n{\n    private string $id;\n    private float $balance = 0;\n    private array $events = [];\n    \n    public static function open(string $id, float $initialBalance): self\n    {\n        $account = new self();\n        $account->id = $id;\n        $account->recordEvent(new MoneyAdded($id, $initialBalance, 'USD', new DateTimeImmutable()));\n        return $account;\n    }\n    \n    public function deposit(float $amount): void\n    {\n        $this->recordEvent(new MoneyAdded($this->id, $amount, 'USD', new DateTimeImmutable()));\n    }\n    \n    public function withdraw(float $amount): void\n    {\n        if ($this->balance \u003C $amount) {\n            throw new InsufficientFundsException();\n        }\n        $this->recordEvent(new MoneySubtracted($this->id, $amount, 'USD', new DateTimeImmutable()));\n    }\n    \n    private function recordEvent($event): void\n    {\n        $this->events[] = $event;\n        $this->apply($event);\n    }\n    \n    private function apply($event): void\n    {\n        if ($event instanceof MoneyAdded) {\n            $this->balance += $event->amount;\n        } elseif ($event instanceof MoneySubtracted) {\n            $this->balance -= $event->amount;\n        }\n    }\n    \n    public function getEvents(): array\n    {\n        return $this->events;\n    }\n    \n    public static function reconstitute(array $events): self\n    {\n        $account = new self();\n        foreach ($events as $event) {\n            $account->apply($event);\n        }\n        return $account;\n    }\n}\n\n\u002F\u002F Event Store\nclass EventStore\n{\n    public function __construct(private DB $db) {}\n    \n    public function save(string $aggregateId, array $events): void\n    {\n        foreach ($events as $event) {\n            $this->db->table('events')->insert([\n                'aggregate_id' => $aggregateId,\n                'type' => get_class($event),\n                'payload' => json_encode($event),\n                'created_at' => now(),\n            ]);\n        }\n    }\n    \n    public function getEventsFor(string $aggregateId): array\n    {\n        $records = $this->db->table('events')\n            ->where('aggregate_id', $aggregateId)\n            ->orderBy('id')\n            ->get();\n            \n        return $records->map(function ($record) {\n            return unserialize($record->payload);\n        })->toArray();\n    }\n}\n\n\u002F\u002F Usage\n$account = BankAccount::open('acc-123', 1000);\n$account->deposit(500);\n$account->withdraw(200);\n\n\u002F\u002F Store events\neventStore->save('acc-123', $account->getEvents());\n\n\u002F\u002F Later, reconstitute\n$events = eventStore->getEventsFor('acc-123');\n$reconstitutedAccount = BankAccount::reconstitute($events);\n```\n\n**Projections (Read Models):**\n\n```php\nclass AccountBalanceProjector\n{\n    public function projectMoneyAdded(MoneyAdded $event): void\n    {\n        DB::table('account_balances')\n            ->updateOrInsert(\n                ['account_id' => $event->accountId],\n                ['balance' => DB::raw(\"balance + {$event->amount}\")]\n            );\n    }\n    \n    public function projectMoneySubtracted(MoneySubtracted $event): void\n    {\n        DB::table('account_balances')\n            ->where('account_id', $event->accountId)\n            ->decrement('balance', $event->amount);\n    }\n}\n```\n\n**Using Laravel Event Sourcing Package:**\n\n```bash\ncomposer require spatie\u002Flaravel-event-sourcing\nphp artisan event-sourcing:install\n```\n\n```php\n\u002F\u002F Aggregate Root\nuse Spatie\\EventSourcing\\AggregateRoots\\AggregateRoot;\n\nclass AccountAggregate extends AggregateRoot\n{\n    private float $balance = 0;\n    \n    public function createAccount(string $id, float $initialBalance): self\n    {\n        $this->recordThat(new AccountCreated($id, $initialBalance));\n        return $this;\n    }\n    \n    public function deposit(float $amount): self\n    {\n        $this->recordThat(new MoneyDeposited($amount));\n        return $this;\n    }\n    \n    protected function applyAccountCreated(AccountCreated $event): void\n    {\n        $this->balance = $event->initialBalance;\n    }\n    \n    protected function applyMoneyDeposited(MoneyDeposited $event): void\n    {\n        $this->balance += $event->amount;\n    }\n}\n\n\u002F\u002F Event Handler\nclass AccountCreatedHandler\n{\n    public function __invoke(AccountCreated $event): void\n    {\n        Account::create([\n            'uuid' => $event->aggregateUuid(),\n            'balance' => $event->initialBalance,\n        ]);\n    }\n}\n\n\u002F\u002F Usage\nAccountAggregate::retrieve('acc-123')\n    ->createAccount('acc-123', 1000)\n    ->deposit(500)\n    ->persist();\n```\n\n**Event Sourcing with Queues:**\n\n```php\nclass AccountAggregate extends AggregateRoot\n{\n    public function deposit(float $amount): self\n    {\n        $this->recordThat(new MoneyDeposited($amount));\n        return $this;\n    }\n}\n\n\u002F\u002F Handle events asynchronously\nclass MoneyDepositedHandler implements ShouldQueue\n{\n    public function handle(MoneyDeposited $event): void\n    {\n        \u002F\u002F Update read model\n        DB::table('accounts')->where('id', $event->aggregateUuid())\n            ->increment('balance', $event->amount);\n    }\n}\n```\n\n**Benefits:**\n- Complete audit trail\n- Ability to rebuild state\n- Temporal queries (state at any point in time)\n- Event replay for debugging\n\n**Drawbacks:**\n- Increased complexity\n- Eventual consistency\n- Storage growth over time\n- Learning curve\n\n**Best Practices:**\n- Keep events small and immutable\n- Version your events\n- Use UUIDs for aggregate IDs\n- Implement snapshotting for large aggregates\n- Handle event versioning gracefully\n\n**Snapshotting:**\n\n```php\nclass AccountAggregate extends AggregateRoot\n{\n    public function shouldTakeSnapshot(): bool\n    {\n        return $this->getAppliedEventsCount() % 100 === 0;\n    }\n    \n    protected function serializeForSnapshot(): array\n    {\n        return ['balance' => $this->balance];\n    }\n    \n    protected static function deserializeFromSnapshot(array $data): self\n    {\n        $aggregate = new self();\n        $aggregate->balance = $data['balance'];\n        return $aggregate;\n    }\n}\n```\n\n**Follow-up Questions:**\n- How do you handle event versioning?\n- How do you migrate event data?\n- What's the difference between event sourcing and CQRS?",[399,400,401,20],"Event Sourcing","CQRS","Domain Events",{"id":403,"category":380,"question":404,"answer":405,"level":343,"tags":406},52,"How do you implement CQRS (Command Query Responsibility Segregation) in Laravel?","CQRS separates read and write operations into different models, optimizing each for its purpose.\n\n**Basic CQRS Structure:**\n\n```php\n\u002F\u002F Commands (Write operations)\nclass CreateOrderCommand\n{\n    public function __construct(\n        public string $userId,\n        public array $items,\n        public string $paymentMethod\n    ) {}\n}\n\nclass UpdateOrderStatusCommand\n{\n    public function __construct(\n        public string $orderId,\n        public string $status\n    ) {}\n}\n\n\u002F\u002F Command Handlers\nclass CreateOrderHandler\n{\n    public function handle(CreateOrderCommand $command): string\n    {\n        DB::beginTransaction();\n        \n        try {\n            $order = Order::create([\n                'user_id' => $command->userId,\n                'items' => json_encode($command->items),\n                'payment_method' => $command->paymentMethod,\n                'status' => 'pending',\n            ]);\n            \n            \u002F\u002F Process payment, update inventory, etc.\n            \n            DB::commit();\n            \n            \u002F\u002F Dispatch event to update read model\n            OrderCreated::dispatch($order->id);\n            \n            return $order->id;\n        } catch (\\Exception $e) {\n            DB::rollBack();\n            throw $e;\n        }\n    }\n}\n\n\u002F\u002F Queries (Read operations)\nclass GetOrderQuery\n{\n    public function __construct(public string $orderId) {}\n}\n\nclass GetUserOrdersQuery\n{\n    public function __construct(\n        public string $userId,\n        public int $page = 1,\n        public int $perPage = 15\n    ) {}\n}\n\n\u002F\u002F Query Handlers (uses read-optimized models)\nclass GetOrderHandler\n{\n    public function handle(GetOrderQuery $query): array\n    {\n        \u002F\u002F Use read-optimized table\u002Fview\n        return DB::table('order_read_model')\n            ->where('id', $query->orderId)\n            ->first();\n    }\n}\n\n\u002F\u002F Controller\nclass OrderController\n{\n    public function __construct(\n        private CommandBus $commandBus,\n        private QueryBus $queryBus\n    ) {}\n    \n    public function store(CreateOrderRequest $request)\n    {\n        $orderId = $this->commandBus->dispatch(\n            new CreateOrderCommand(\n                userId: auth()->id(),\n                items: $request->items,\n                paymentMethod: $request->payment_method\n            )\n        );\n        \n        return response()->json(['order_id' => $orderId], 201);\n    }\n    \n    public function show($id)\n    {\n        $order = $this->queryBus->dispatch(new GetOrderQuery($id));\n        \n        if (!$order) {\n            abort(404);\n        }\n        \n        return response()->json($order);\n    }\n}\n```\n\n**Separate Read\u002FWrite Models:**\n\n```php\n\u002F\u002F Write model (Normalized, for updates)\nclass Order extends Model\n{\n    protected $table = 'orders';\n    \n    public function items()\n    {\n        return $this->hasMany(OrderItem::class);\n    }\n}\n\n\u002F\u002F Read model (Denormalized, for queries)\nclass OrderReadModel extends Model\n{\n    protected $table = 'order_denormalized';\n    protected $primaryKey = 'id';\n    public $timestamps = false;\n    \n    \u002F\u002F No relationships, just data\n}\n\n\u002F\u002F Projector to keep read model in sync\nclass OrderProjector\n{\n    public function onOrderCreated(OrderCreated $event): void\n    {\n        DB::table('order_denormalized')->insert([\n            'id' => $event->orderId,\n            'user_name' => $event->userName,\n            'total' => $event->total,\n            'item_count' => count($event->items),\n            'status' => 'pending',\n            'created_at' => now(),\n        ]);\n    }\n    \n    public function onOrderStatusUpdated(OrderStatusUpdated $event): void\n    {\n        DB::table('order_denormalized')\n            ->where('id', $event->orderId)\n            ->update(['status' => $event->status]);\n    }\n}\n```\n\n**Simple Command Bus Implementation:**\n\n```php\nclass CommandBus\n{\n    private array $handlers = [];\n    \n    public function register(string $command, string $handler): void\n    {\n        $this->handlers[$command] = $handler;\n    }\n    \n    public function dispatch($command)\n    {\n        $handlerClass = $this->handlers[get_class($command)];\n        $handler = app($handlerClass);\n        \n        return $handler->handle($command);\n    }\n}\n\n\u002F\u002F Register in service provider\npublic function boot(): void\n{\n    $this->app->make(CommandBus::class)->register(\n        CreateOrderCommand::class,\n        CreateOrderHandler::class\n    );\n}\n```\n\n**Advanced CQRS with Event Sourcing:**\n\n```php\n\u002F\u002F Command\nclass DepositMoneyCommand\n{\n    public function __construct(\n        public string $accountId,\n        public float $amount,\n        public string $reference\n    ) {}\n}\n\n\u002F\u002F Handler using event sourcing\nclass DepositMoneyHandler\n{\n    public function handle(DepositMoneyCommand $command): void\n    {\n        AccountAggregate::retrieve($command->accountId)\n            ->deposit($command->amount, $command->reference)\n            ->persist();\n    }\n}\n\n\u002F\u002F Query\nclass GetAccountBalanceQuery\n{\n    public function __construct(public string $accountId) {}\n}\n\n\u002F\u002F Query handler uses projection\nclass GetAccountBalanceHandler\n{\n    public function handle(GetAccountBalanceQuery $query): float\n    {\n        return DB::table('account_balances')\n            ->where('account_id', $query->accountId)\n            ->value('balance') ?? 0;\n    }\n}\n```\n\n**CQRS with Repository Pattern:**\n\n```php\n\u002F\u002F Write repository\ninterface OrderWriteRepository\n{\n    public function save(Order $order): void;\n    public function findById(string $id): Order;\n}\n\n\u002F\u002F Read repository\ninterface OrderReadRepository\n{\n    public function findById(string $id): OrderReadModel;\n    public function getByUser(string $userId, int $page, int $perPage): array;\n    public function getByStatus(string $status, array $filters): LengthAwarePaginator;\n}\n\n\u002F\u002F Implementation\nclass EloquentOrderReadRepository implements OrderReadRepository\n{\n    public function findById(string $id): OrderReadModel\n    {\n        return OrderReadModel::findOrFail($id);\n    }\n    \n    public function getByUser(string $userId, int $page, int $perPage): array\n    {\n        return OrderReadModel::where('user_id', $userId)\n            ->orderBy('created_at', 'desc')\n            ->paginate($perPage)\n            ->toArray();\n    }\n}\n```\n\n**Benefits of CQRS:**\n- Independent scaling of reads and writes\n- Optimized data models for each operation\n- Simplified write models (no complex queries)\n- Better performance for read-heavy applications\n\n**Drawbacks:**\n- Increased complexity\n- Eventual consistency\n- Duplicate code\n- Learning curve\n\n**When to Use CQRS:**\n- High read\u002Fwrite ratio (e.g., social media feeds)\n- Complex domain logic\n- Scalability requirements\n- Team experience with patterns\n\n**When NOT to Use:**\n- Simple CRUD applications\n- Small teams\u002Fprojects\n- Real-time consistency requirements\n\n**Best Practices:**\n- Start with simple separation, add complexity gradually\n- Use events to sync read models\n- Accept eventual consistency\n- Monitor read model rebuild time\n- Version your read models\n\n**Follow-up Questions:**\n- How do you handle eventual consistency in UI?\n- How do you migrate existing apps to CQRS?\n- What's the difference between CQRS and event sourcing?",[400,20,407,408],"Command Bus","Query Optimization",{"id":410,"category":380,"question":411,"answer":412,"level":343,"tags":413},53,"How do you implement a message broker with RabbitMQ in Laravel?","RabbitMQ provides advanced message queuing with routing, exchanges, and message acknowledgments.\n\n**Installation:**\n\n```bash\ncomposer require vladimir-yuldashev\u002Flaravel-queue-rabbitmq\n```\n\n**Configuration:**\n\n```php\n\u002F\u002F config\u002Fqueue.php\n'connections' => [\n    'rabbitmq' => [\n        'driver' => 'rabbitmq',\n        'host' => env('RABBITMQ_HOST', 'localhost'),\n        'port' => env('RABBITMQ_PORT', 5672),\n        'vhost' => env('RABBITMQ_VHOST', '\u002F'),\n        'login' => env('RABBITMQ_LOGIN', 'guest'),\n        'password' => env('RABBITMQ_PASSWORD', 'guest'),\n        'queue' => env('RABBITMQ_QUEUE', 'default'),\n        'exchange' => env('RABBITMQ_EXCHANGE', 'laravel_exchange'),\n        'exchange_type' => env('RABBITMQ_EXCHANGE_TYPE', 'direct'),\n        'exchange_durable' => true,\n        'queue_durable' => true,\n    ],\n],\n```\n\n**Basic Usage:**\n\n```php\n\u002F\u002F Create job\nclass ProcessOrder implements ShouldQueue\n{\n    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;\n    \n    public function __construct(public Order $order) {}\n    \n    public function handle(): void\n    {\n        \u002F\u002F Process order\n    }\n}\n\n\u002F\u002F Dispatch to RabbitMQ\nProcessOrder::dispatch($order)->onConnection('rabbitmq');\n```\n\n**Exchanges and Routing Keys:**\n\n```php\n\u002F\u002F Direct exchange\nclass SendEmail implements ShouldQueue\n{\n    public function __construct(public string $email) {}\n    \n    public function viaQueue(): string\n    {\n        return 'emails'; \u002F\u002F Routing key\n    }\n}\n\n\u002F\u002F Publish to specific exchange\nQueue::connection('rabbitmq')->pushRaw('message', 'emails', 'email_exchange');\n```\n\n**Custom RabbitMQ Publisher:**\n\n```php\nuse PhpAmqpLib\\Connection\\AMQPStreamConnection;\nuse PhpAmqpLib\\Message\\AMQPMessage;\n\nclass RabbitMQPublisher\n{\n    private $connection;\n    private $channel;\n    \n    public function __construct()\n    {\n        $this->connection = new AMQPStreamConnection(\n            config('queue.connections.rabbitmq.host'),\n            config('queue.connections.rabbitmq.port'),\n            config('queue.connections.rabbitmq.login'),\n            config('queue.connections.rabbitmq.password'),\n            config('queue.connections.rabbitmq.vhost')\n        );\n        \n        $this->channel = $this->connection->channel();\n    }\n    \n    public function publish(string $exchange, string $routingKey, array $data): void\n    {\n        $message = new AMQPMessage(\n            json_encode($data),\n            [\n                'content_type' => 'application\u002Fjson',\n                'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,\n            ]\n        );\n        \n        $this->channel->basic_publish($message, $exchange, $routingKey);\n    }\n    \n    public function consume(string $queue, callable $callback): void\n    {\n        $this->channel->basic_consume($queue, '', false, false, false, false, function ($message) use ($callback) {\n            $callback(json_decode($message->body, true));\n            $message->ack();\n        });\n        \n        while ($this->channel->is_consuming()) {\n            $this->channel->wait();\n        }\n    }\n    \n    public function __destruct()\n    {\n        $this->channel->close();\n        $this->connection->close();\n    }\n}\n\n\u002F\u002F Usage\n$publisher = new RabbitMQPublisher();\n$publisher->publish('user_exchange', 'user.created', ['id' => 1, 'email' => 'user@example.com']);\n```\n\n**Topic Exchange (Routing based on pattern):**\n\n```php\n\u002F\u002F config\u002Fqueue.php\n'exchange_type' => 'topic',\n\n\u002F\u002F Publishing\n$publisher->publish('logs', 'user.created', ['user_id' => 1]);\n$publisher->publish('logs', 'order.placed', ['order_id' => 100]);\n\n\u002F\u002F Consumers\n\u002F\u002F Consumer 1: All user events (user.*)\n\u002F\u002F Consumer 2: All events (#)\n\u002F\u002F Consumer 3: Only user created events (user.created)\n```\n\n**Fanout Exchange (Broadcast to all queues):**\n\n```php\n\u002F\u002F config\u002Fqueue.php\n'exchange_type' => 'fanout',\n\n\u002F\u002F All bound queues receive every message\n$publisher->publish('broadcast', '', ['message' => 'Hello everyone']);\n```\n\n**Headers Exchange (Routing based on headers):**\n\n```php\n\u002F\u002F config\u002Fqueue.php\n'exchange_type' => 'headers',\n\n$message = new AMQPMessage(\n    json_encode($data),\n    [\n        'headers' => ['format' => 'pdf', 'type' => 'report'],\n    ]\n);\n```\n\n**Dead Letter Exchanges (Handling failures):**\n\n```php\n\u002F\u002F Queue configuration with DLX\n$this->channel->queue_declare(\n    'main_queue',\n    false,\n    true,\n    false,\n    false,\n    false,\n    new AMQPTable([\n        'x-dead-letter-exchange' => 'dlx_exchange',\n        'x-dead-letter-routing-key' => 'failed',\n        'x-max-retries' => 3,\n    ])\n);\n\n\u002F\u002F Dead letter queue\n$this->channel->queue_declare('failed_queue', false, true, false, false);\n$this->channel->queue_bind('failed_queue', 'dlx_exchange', 'failed');\n```\n\n**Message Acknowledgments and Rejections:**\n\n```php\nclass ProcessOrder implements ShouldQueue\n{\n    public function handle(): void\n    {\n        try {\n            \u002F\u002F Process\n            $this->delete(); \u002F\u002F Acknowledge\n        } catch (RetryException $e) {\n            $this->release(10); \u002F\u002F Reject and requeue\n        } catch (PermanentException $e) {\n            $this->fail($e); \u002F\u002F Reject and send to DLX\n        }\n    }\n}\n```\n\n**Monitoring RabbitMQ:**\n\n```php\n\u002F\u002F Get queue stats\n$stats = $this->channel->queue_declare('queue_name', true);\n$messageCount = $stats[1];\n$consumerCount = $stats[2];\n\n\u002F\u002F Management API (if enabled)\n$client = new GuzzleHttp\\Client();\n$response = $client->get('http:\u002F\u002Flocalhost:15672\u002Fapi\u002Fqueues', [\n    'auth' => ['guest', 'guest'],\n]);\n```\n\n**RPC Pattern (Request-Response):**\n\n```php\nclass RpcClient\n{\n    private $connection;\n    private $channel;\n    private $callbackQueue;\n    private $response;\n    \n    public function call(string $routingKey, array $data): mixed\n    {\n        $correlationId = uniqid();\n        \n        list($this->callbackQueue) = $this->channel->queue_declare('', false, false, true, false);\n        \n        $this->channel->basic_consume(\n            $this->callbackQueue,\n            '',\n            false,\n            true,\n            false,\n            false,\n            function ($message) use ($correlationId) {\n                if ($message->get('correlation_id') == $correlationId) {\n                    $this->response = json_decode($message->body, true);\n                }\n            }\n        );\n        \n        $message = new AMQPMessage(\n            json_encode($data),\n            [\n                'correlation_id' => $correlationId,\n                'reply_to' => $this->callbackQueue,\n            ]\n        );\n        \n        $this->channel->basic_publish($message, '', $routingKey);\n        \n        while (!$this->response) {\n            $this->channel->wait();\n        }\n        \n        return $this->response;\n    }\n}\n```\n\n**Best Practices:**\n- Use persistent messages for important data\n- Implement idempotent consumers\n- Set appropriate prefetch counts\n- Monitor queue depths\n- Use dead letter exchanges for failed messages\n\n**Performance:** RabbitMQ can handle 50,000+ messages per second with proper configuration.\n\n**Follow-up Questions:**\n- How do you handle duplicate messages?\n- What's your strategy for message ordering?\n- How do you secure RabbitMQ in production?",[414,415,416,417],"RabbitMQ","Message Queue","Broker","Microservices",{"id":419,"category":380,"question":420,"answer":421,"level":343,"tags":422},54,"How do you implement WebSocket broadcasting with Laravel and Pusher?","WebSocket broadcasting enables real-time features by pushing updates from server to client without polling.\n\n**Installation:**\n\n```bash\ncomposer require pusher\u002Fpusher-php-server\nphp artisan install:broadcasting\n```\n\n**Configuration:**\n\n```php\n\u002F\u002F config\u002Fbroadcasting.php\n'connections' => [\n    'pusher' => [\n        'driver' => 'pusher',\n        'key' => env('PUSHER_APP_KEY'),\n        'secret' => env('PUSHER_APP_SECRET'),\n        'app_id' => env('PUSHER_APP_ID'),\n        'options' => [\n            'cluster' => env('PUSHER_APP_CLUSTER'),\n            'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',\n            'port' => env('PUSHER_PORT', 443),\n            'scheme' => env('PUSHER_SCHEME', 'https'),\n            'encrypted' => true,\n            'useTLS' => true,\n        ],\n    ],\n],\n```\n\n**Creating Broadcast Events:**\n\n```php\n\u002F\u002F app\u002FEvents\u002FOrderShipped.php\nuse Illuminate\\Broadcasting\\Channel;\nuse Illuminate\\Broadcasting\\InteractsWithSockets;\nuse Illuminate\\Broadcasting\\PresenceChannel;\nuse Illuminate\\Broadcasting\\PrivateChannel;\nuse Illuminate\\Contracts\\Broadcasting\\ShouldBroadcast;\nuse Illuminate\\Foundation\\Events\\Dispatchable;\nuse Illuminate\\Queue\\SerializesModels;\n\nclass OrderShipped implements ShouldBroadcast\n{\n    use Dispatchable, InteractsWithSockets, SerializesModels;\n    \n    public function __construct(public Order $order)\n    {\n        $this->order = $order;\n    }\n    \n    public function broadcastOn(): array\n    {\n        return [\n            new PrivateChannel('orders.' . $this->order->user_id),\n        ];\n    }\n    \n    public function broadcastAs(): string\n    {\n        return 'order.shipped';\n    }\n    \n    public function broadcastWith(): array\n    {\n        return [\n            'id' => $this->order->id,\n            'status' => $this->order->status,\n            'tracking_number' => $this->order->tracking_number,\n        ];\n    }\n}\n\n\u002F\u002F Dispatch event\nOrderShipped::dispatch($order);\n```\n\n**Client-Side Setup (Laravel Echo):**\n\n```javascript\n\u002F\u002F resources\u002Fjs\u002Fbootstrap.js\nimport Echo from 'laravel-echo';\nimport Pusher from 'pusher-js';\n\nwindow.Pusher = Pusher;\n\nwindow.Echo = new Echo({\n    broadcaster: 'pusher',\n    key: import.meta.env.VITE_PUSHER_APP_KEY,\n    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,\n    forceTLS: true,\n    authEndpoint: '\u002Fbroadcasting\u002Fauth',\n});\n\n\u002F\u002F Listen to public channel\nwindow.Echo.channel('public-channel')\n    .listen('OrderShipped', (e) => {\n        console.log('Order shipped:', e.order);\n    });\n\n\u002F\u002F Listen to private channel\nwindow.Echo.private(`orders.${userId}`)\n    .listen('OrderShipped', (e) => {\n        console.log('Your order shipped:', e);\n    });\n\n\u002F\u002F Listen to presence channel\nwindow.Echo.join(`chat.${roomId}`)\n    .here((users) => {\n        console.log('Online users:', users);\n    })\n    .joining((user) => {\n        console.log('User joined:', user);\n    })\n    .leaving((user) => {\n        console.log('User left:', user);\n    })\n    .listen('MessageSent', (e) => {\n        console.log('New message:', e.message);\n    });\n```\n\n**Presence Channels:**\n\n```php\n\u002F\u002F app\u002FEvents\u002FChatMessage.php\nclass ChatMessage implements ShouldBroadcast\n{\n    use Dispatchable, InteractsWithSockets, SerializesModels;\n    \n    public function __construct(\n        public Room $room,\n        public User $user,\n        public string $message\n    ) {}\n    \n    public function broadcastOn(): array\n    {\n        return [new PresenceChannel('chat.' . $this->room->id)];\n    }\n    \n    public function broadcastWith(): array\n    {\n        return [\n            'user' => [\n                'id' => $this->user->id,\n                'name' => $this->user->name,\n            ],\n            'message' => $this->message,\n            'timestamp' => now()->toIso8601String(),\n        ];\n    }\n}\n\n\u002F\u002F Authorization for presence channel\n\u002F\u002F routes\u002Fchannels.php\nBroadcast::channel('chat.{roomId}', function ($user, $roomId) {\n    $room = Room::find($roomId);\n    \n    if ($room->hasMember($user)) {\n        return [\n            'id' => $user->id,\n            'name' => $user->name,\n            'avatar' => $user->avatar_url,\n        ];\n    }\n    \n    return false;\n});\n```\n\n**Client Events (Whisper):**\n\n```javascript\n\u002F\u002F Send client event\nwindow.Echo.private(`chat.${roomId}`)\n    .whisper('typing', {\n        user: userId,\n        isTyping: true\n    });\n\n\u002F\u002F Listen for client events\nwindow.Echo.private(`chat.${roomId}`)\n    .listenForWhisper('typing', (e) => {\n        console.log(`${e.user} is typing...`);\n    });\n```\n\n**Authentication for Private Channels:**\n\n```php\n\u002F\u002F routes\u002Fchannels.php\nuse Illuminate\\Support\\Facades\\Broadcast;\n\nBroadcast::channel('orders.{userId}', function ($user, $userId) {\n    return (int) $user->id === (int) $userId;\n});\n\n\u002F\u002F With custom authorization logic\nBroadcast::channel('team.{teamId}', function ($user, $teamId) {\n    $team = Team::find($teamId);\n    \n    return $team->hasMember($user) ? [\n        'id' => $user->id,\n        'name' => $user->name,\n        'role' => $team->getUserRole($user),\n    ] : false;\n});\n```\n\n**Using Pusher with Laravel WebSockets (Self-hosted):**\n\n```bash\ncomposer require beyondcode\u002Flaravel-websockets\nphp artisan vendor:publish --provider=\"BeyondCode\\LaravelWebSockets\\WebSocketsServiceProvider\" --tag=\"config\"\nphp artisan migrate\n```\n\n```php\n\u002F\u002F config\u002Fbroadcasting.php\n'pusher' => [\n    'driver' => 'pusher',\n    'key' => env('PUSHER_APP_KEY'),\n    'secret' => env('PUSHER_APP_SECRET'),\n    'app_id' => env('PUSHER_APP_ID'),\n    'options' => [\n        'host' => '127.0.0.1',\n        'port' => 6001,\n        'scheme' => 'http',\n        'encrypted' => false,\n        'useTLS' => false,\n    ],\n],\n\n\u002F\u002F config\u002Fwebsockets.php\n'apps' => [\n    [\n        'id' => env('PUSHER_APP_ID'),\n        'name' => env('APP_NAME'),\n        'key' => env('PUSHER_APP_KEY'),\n        'secret' => env('PUSHER_APP_SECRET'),\n        'path' => env('PUSHER_APP_PATH'),\n        'capacity' => null,\n        'enable_client_messages' => true,\n        'enable_statistics' => true,\n    ],\n],\n```\n\n**Real-World Example: Notification System:**\n\n```php\n\u002F\u002F app\u002FEvents\u002FNewNotification.php\nclass NewNotification implements ShouldBroadcast\n{\n    public function __construct(public User $user, public array $notification) {}\n    \n    public function broadcastOn(): array\n    {\n        return [new PrivateChannel('notifications.' . $this->user->id)];\n    }\n    \n    public function broadcastAs(): string\n    {\n        return 'notification.new';\n    }\n    \n    public function broadcastWith(): array\n    {\n        return $this->notification;\n    }\n}\n\n\u002F\u002F Controller\npublic function markAsRead($id)\n{\n    $notification = auth()->user()->notifications()->find($id);\n    $notification->markAsRead();\n    \n    \u002F\u002F Broadcast count update\n    broadcast(new NotificationCountUpdated(auth()->user(), auth()->user()->unreadNotifications->count()));\n    \n    return response()->json(['success' => true]);\n}\n\n\u002F\u002F JavaScript\nwindow.Echo.private(`notifications.${userId}`)\n    .listen('notification.new', (notification) => {\n        addNotificationToUI(notification);\n        updateBadgeCount();\n    })\n    .listen('notification.count.updated', (data) => {\n        updateBadgeCount(data.count);\n    });\n```\n\n**Performance Optimization:**\n\n```php\n\u002F\u002F Queue broadcast events\nevent(new OrderShipped($order)); \u002F\u002F Automatically queued if ShouldBroadcast interface\n\n\u002F\u002F Throttle broadcasts\nRateLimiter::for('broadcast', function ($event) {\n    return Limit::perMinute(60);\n});\n\n\u002F\u002F Custom broadcast connection\nclass OrderShipped implements ShouldBroadcast\n{\n    public function broadcastConnection()\n    {\n        return 'redis'; \u002F\u002F Use Redis for broadcasting\n    }\n}\n```\n\n**Security Best Practices:**\n- Always authorize private\u002Fpresence channels\n- Use signed URLs for socket connections\n- Implement rate limiting on broadcasts\n- Don't send sensitive data through WebSockets\n- Validate all client-sent data\n\n**Monitoring:**\n\n```php\n\u002F\u002F Log broadcasting events\nEvent::listen(MessageSent::class, function ($event) {\n    Log::info('Broadcasting event', [\n        'channel' => $event->broadcastOn(),\n        'event' => get_class($event),\n    ]);\n});\n```\n\n**Follow-up Questions:**\n- How do you handle offline clients?\n- What's the maximum concurrent connections supported?\n- How do you scale WebSocket servers horizontally?",[423,424,425,426],"WebSockets","Broadcasting","Pusher","Real-time",{"id":428,"category":380,"question":429,"answer":430,"level":343,"tags":431},55,"How do you implement Elasticsearch integration with Laravel for advanced search?","Elasticsearch provides powerful full-text search capabilities beyond MySQL's LIKE queries.\n\n**Installation:**\n\n```bash\ncomposer require elasticsearch\u002Felasticsearch\n```\n\n**Configuration:**\n\n```php\n\u002F\u002F config\u002Felasticsearch.php\nreturn [\n    'hosts' => [\n        env('ELASTICSEARCH_HOST', 'localhost:9200'),\n    ],\n    'retries' => 2,\n    'indices' => [\n        'posts' => 'posts_index',\n        'users' => 'users_index',\n    ],\n];\n\n\u002F\u002F AppServiceProvider\nuse Elastic\\Elasticsearch\\ClientBuilder;\n\npublic function register()\n{\n    $this->app->singleton(ElasticsearchClient::class, function ($app) {\n        return ClientBuilder::create()\n            ->setHosts(config('elasticsearch.hosts'))\n            ->setRetries(config('elasticsearch.retries'))\n            ->build();\n    });\n}\n```\n\n**Indexing Models:**\n\n```php\n\u002F\u002F app\u002FModels\u002FPost.php\nuse Elastic\\Elasticsearch\\Client;\n\nclass Post extends Model\n{\n    public static function boot()\n    {\n        parent::boot();\n        \n        static::created(function ($post) {\n            $post->indexToElasticsearch();\n        });\n        \n        static::updated(function ($post) {\n            $post->indexToElasticsearch();\n        });\n        \n        static::deleted(function ($post) {\n            $post->removeFromElasticsearch();\n        });\n    }\n    \n    public function indexToElasticsearch()\n    {\n        $client = app(Client::class);\n        \n        $client->index([\n            'index' => 'posts',\n            'id' => $this->id,\n            'body' => [\n                'id' => $this->id,\n                'title' => $this->title,\n                'content' => $this->content,\n                'author' => $this->author->name,\n                'tags' => $this->tags->pluck('name'),\n                'created_at' => $this->created_at->toISOString(),\n            ],\n        ]);\n    }\n    \n    public function removeFromElasticsearch()\n    {\n        $client = app(Client::class);\n        \n        $client->delete([\n            'index' => 'posts',\n            'id' => $this->id,\n        ]);\n    }\n    \n    public static function search($query, $filters = [])\n    {\n        $client = app(Client::class);\n        \n        $params = [\n            'index' => 'posts',\n            'body' => [\n                'query' => [\n                    'bool' => [\n                        'must' => [\n                            'multi_match' => [\n                                'query' => $query,\n                                'fields' => ['title^3', 'content', 'author'],\n                                'fuzziness' => 'AUTO',\n                            ],\n                        ],\n                        'filter' => $this->buildFilters($filters),\n                    ],\n                ],\n                'sort' => [\n                    '_score' => 'desc',\n                    'created_at' => 'desc',\n                ],\n                'from' => ($filters['page'] - 1) * $filters['per_page'] ?? 0,\n                'size' => $filters['per_page'] ?? 10,\n            ],\n        ];\n        \n        $response = $client->search($params);\n        \n        $ids = collect($response['hits']['hits'])->pluck('_id');\n        \n        return static::whereIn('id', $ids)\n            ->orderByRaw('FIELD(id, ' . implode(',', $ids->toArray()) . ')')  \n            ->get();\n    }\n    \n    private function buildFilters($filters)\n    {\n        $filterQuery = [];\n        \n        if (!empty($filters['category_id'])) {\n            $filterQuery[] = [\n                'term' => ['category_id' => $filters['category_id']]\n            ];\n        }\n        \n        if (!empty($filters['date_from'])) {\n            $filterQuery[] = [\n                'range' => ['created_at' => ['gte' => $filters['date_from']]]\n            ];\n        }\n        \n        return $filterQuery;\n    }\n}\n\n\u002F\u002F Usage\n$posts = Post::search('laravel framework', [\n    'category_id' => 5,\n    'page' => 1,\n    'per_page' => 20,\n]);\n```\n\n**Creating Indexes and Mappings:**\n\n```php\n\u002F\u002F Artisan command\nphp artisan make:command CreateElasticsearchIndex\n\nclass CreateElasticsearchIndex extends Command\n{\n    public function handle()\n    {\n        $client = app(Client::class);\n        \n        $params = [\n            'index' => 'posts',\n            'body' => [\n                'settings' => [\n                    'number_of_shards' => 3,\n                    'number_of_replicas' => 1,\n                    'analysis' => [\n                        'analyzer' => [\n                            'custom_analyzer' => [\n                                'type' => 'custom',\n                                'tokenizer' => 'standard',\n                                'filter' => ['lowercase', 'stop', 'snowball'],\n                            ],\n                        ],\n                    ],\n                ],\n                'mappings' => [\n                    'properties' => [\n                        'id' => ['type' => 'integer'],\n                        'title' => [\n                            'type' => 'text',\n                            'analyzer' => 'custom_analyzer',\n                            'fields' => [\n                                'keyword' => ['type' => 'keyword'],\n                            ],\n                        ],\n                        'content' => [\n                            'type' => 'text',\n                            'analyzer' => 'custom_analyzer',\n                        ],\n                        'author' => ['type' => 'text'],\n                        'tags' => ['type' => 'keyword'],\n                        'created_at' => ['type' => 'date'],\n                    ],\n                ],\n            ],\n        ];\n        \n        if ($client->indices()->exists(['index' => 'posts'])) {\n            $client->indices()->delete(['index' => 'posts']);\n        }\n        \n        $client->indices()->create($params);\n        \n        $this->info('Index created successfully');\n    }\n}\n```\n\n**Advanced Search Features:**\n\n```php\n\u002F\u002F Fuzzy search\n$params['body']['query']['fuzzy'] = [\n    'title' => [\n        'value' => $query,\n        'fuzziness' => 'AUTO',\n    ],\n];\n\n\u002F\u002F Autocomplete (prefix search)\n$params['body']['query']['prefix'] = [\n    'title' => $query,\n];\n\n\u002F\u002F Wildcard search\n$params['body']['query']['wildcard'] = [\n    'title' => '*' . $query . '*',\n];\n\n\u002F\u002F Phrase search\n$params['body']['query']['match_phrase'] = [\n    'content' => $query,\n];\n\n\u002F\u002F Highlighting results\n$params['body']['highlight'] = [\n    'fields' => [\n        'title' => new \\stdClass(),\n        'content' => new \\stdClass(),\n    ],\n];\n\n\u002F\u002F Aggregations (facets)\n$params['body']['aggs'] = [\n    'category_agg' => [\n        'terms' => ['field' => 'category_id'],\n    ],\n    'date_histogram' => [\n        'date_histogram' => [\n            'field' => 'created_at',\n            'calendar_interval' => 'month',\n        ],\n    ],\n];\n```\n\n**Bulk Indexing:**\n\n```php\nclass BulkIndexCommand extends Command\n{\n    public function handle()\n    {\n        $client = app(Client::class);\n        $params = ['body' => []];\n        \n        Post::chunk(100, function ($posts) use (&$params, $client) {\n            foreach ($posts as $post) {\n                $params['body'][] = [\n                    'index' => [\n                        '_index' => 'posts',\n                        '_id' => $post->id,\n                    ],\n                ];\n                \n                $params['body'][] = [\n                    'id' => $post->id,\n                    'title' => $post->title,\n                    'content' => $post->content,\n                    'author' => $post->author->name,\n                    'created_at' => $post->created_at->toISOString(),\n                ];\n            }\n            \n            $client->bulk($params);\n            $params = ['body' => []];\n        });\n        \n        $this->info('All posts indexed');\n    }\n}\n```\n\n**Search Service Class:**\n\n```php\nclass SearchService\n{\n    public function __construct(private Client $client) {}\n    \n    public function search(string $query, array $filters, string $model): array\n    {\n        $index = $this->getIndexForModel($model);\n        \n        $response = $this->client->search([\n            'index' => $index,\n            'body' => $this->buildQuery($query, $filters),\n        ]);\n        \n        return $this->formatResults($response);\n    }\n    \n    public function suggest(string $query, string $field): array\n    {\n        $response = $this->client->search([\n            'index' => 'posts',\n            'body' => [\n                'suggest' => [\n                    'suggestions' => [\n                        'prefix' => $query,\n                        'completion' => [\n                            'field' => $field . '_suggest',\n                            'size' => 5,\n                        ],\n                    ],\n                ],\n            ],\n        ]);\n        \n        return $response['suggest']['suggestions'][0]['options'] ?? [];\n    }\n    \n    public function deleteIndex(string $index): void\n    {\n        if ($this->client->indices()->exists(['index' => $index])) {\n            $this->client->indices()->delete(['index' => $index]);\n        }\n    }\n}\n```\n\n**Performance Optimization:**\n\n```php\n\u002F\u002F Use scroll for large result sets\n$response = $client->search([\n    'index' => 'posts',\n    'scroll' => '2m',\n    'size' => 1000,\n    'body' => ['query' => ['match_all' => new \\stdClass()]],\n]);\n\n$scrollId = $response['_scroll_id'];\n\nwhile (true) {\n    $response = $client->scroll([\n        'scroll_id' => $scrollId,\n        'scroll' => '2m',\n    ]);\n    \n    if (empty($response['hits']['hits'])) {\n        break;\n    }\n    \n    foreach ($response['hits']['hits'] as $hit) {\n        \u002F\u002F Process hit\n    }\n}\n\n\u002F\u002F Clear scroll\n$client->clearScroll(['scroll_id' => $scrollId]);\n```\n\n**Best Practices:**\n- Index only searchable fields\n- Use appropriate field types\n- Implement index aliases for zero-downtime reindexing\n- Monitor cluster health\n- Set up index lifecycle management\n\n**Follow-up Questions:**\n- How do you handle reindexing with zero downtime?\n- What's your strategy for keeping Elasticsearch in sync with MySQL?\n- How do you handle Elasticsearch cluster failures?",[432,433,434,435],"Elasticsearch","Search","Full-text Search","Indexing",{"id":437,"category":380,"question":438,"answer":439,"level":343,"tags":440},56,"How do you implement a multi-tenant architecture in Laravel?","Multi-tenancy allows a single application instance to serve multiple customers (tenants) with data isolation.\n\n**Database-per-Tenant Approach:**\n\n```php\n\u002F\u002F config\u002Ftencent.php\nreturn [\n    'tenants' => [\n        'tenant1' => [\n            'database' => 'tenant1_db',\n            'host' => 'localhost',\n        ],\n        'tenant2' => [\n            'database' => 'tenant2_db',\n            'host' => 'localhost',\n        ],\n    ],\n];\n\n\u002F\u002F Tenant Manager\nclass TenantManager\n{\n    protected $currentTenant;\n    \n    public function setTenant($tenant)\n    {\n        $this->currentTenant = $tenant;\n        \n        $config = config(\"tencent.tenants.{$tenant}\");\n        \n        config([\n            'database.connections.tenant' => [\n                'driver' => 'mysql',\n                'host' => $config['host'],\n                'database' => $config['database'],\n                'username' => env('DB_USERNAME'),\n                'password' => env('DB_PASSWORD'),\n            ],\n        ]);\n        \n        DB::purge('tenant');\n        DB::reconnect('tenant');\n        \n        return $this;\n    }\n    \n    public function getTenant()\n    {\n        return $this->currentTenant;\n    }\n    \n    public function connection()\n    {\n        return DB::connection('tenant');\n    }\n}\n\n\u002F\u002F Middleware\nclass TenantMiddleware\n{\n    public function handle($request, $next)\n    {\n        $tenant = $request->getHost();\n        $tenant = explode('.', $tenant)[0]; \u002F\u002F subdomain\n        \n        if (!array_key_exists($tenant, config('tencent.tenants'))) {\n            abort(404);\n        }\n        \n        app(TenantManager::class)->setTenant($tenant);\n        \n        return $next($request);\n    }\n}\n\n\u002F\u002F Models\nclass Post extends Model\n{\n    protected $connection = 'tenant';\n    \n    protected $table = 'posts';\n}\n\n\u002F\u002F Usage\nRoute::middleware(['tenant'])->group(function () {\n    Route::get('\u002Fposts', function () {\n        return Post::all(); \u002F\u002F Uses tenant database\n    });\n});\n```\n\n**Single Database with Tenant Column:**\n\n```php\n\u002F\u002F Migration\nSchema::create('posts', function (Blueprint $table) {\n    $table->id();\n    $table->string('tenant_id');\n    $table->string('title');\n    $table->text('content');\n    $table->timestamps();\n    \n    $table->index('tenant_id');\n});\n\n\u002F\u002F Global Scope\nclass TenantScope implements Scope\n{\n    public function apply(Builder $builder, Model $model)\n    {\n        if ($tenantId = app(TenantManager::class)->getTenant()) {\n            $builder->where('tenant_id', $tenantId);\n        }\n    }\n}\n\n\u002F\u002F Model\nclass Post extends Model\n{\n    protected static function booted()\n    {\n        static::addGlobalScope(new TenantScope);\n        \n        static::creating(function ($post) {\n            $post->tenant_id = app(TenantManager::class)->getTenant();\n        });\n    }\n}\n```\n\n**Using Stancl\u002FTenancy Package:**\n\n```bash\ncomposer require stancl\u002Ftenancy\nphp artisan tenancy:install\nphp artisan migrate\n```\n\n```php\n\u002F\u002F config\u002Ftenancy.php\n'central_domains' => [\n    'saas.app',\n    'localhost',\n],\n\n\u002F\u002F Tenant Model\nuse Stancl\\Tenancy\\Database\\Models\\Tenant as BaseTenant;\n\nclass Tenant extends BaseTenant\n{\n    public static function getCustomColumns(): array\n    {\n        return [\n            'id',\n            'plan',\n            'domain',\n        ];\n    }\n}\n\n\u002F\u002F Create tenant\n$tenant = Tenant::create([\n    'id' => 'tenant1',\n    'plan' => 'premium',\n    'domain' => 'tenant1.saas.app',\n]);\n\n$tenant->domains()->create(['domain' => 'tenant1.saas.app']);\n\n\u002F\u002F Automatic tenant detection\n\u002F\u002F Access tenant1.saas.app -> automatically uses tenant1 database\n\n\u002F\u002F Manual tenant switching\ntenancy()->initialize($tenant);\n```\n\n**Tenant Data Isolation Strategies:**\n\n```php\n\u002F\u002F 1. Schema-based (PostgreSQL)\nclass SchemaTenantManager\n{\n    public function setTenant($tenant)\n    {\n        DB::statement(\"SET search_path TO {$tenant}\");\n    }\n}\n\n\u002F\u002F 2. Database prefix\nclass PrefixTenantManager\n{\n    public function setTenant($tenant)\n    {\n        $prefix = $tenant . '_';\n        \n        DB::connection()->setTablePrefix($prefix);\n    }\n}\n\n\u002F\u002F 3. Redis namespace\nclass RedisTenantManager\n{\n    public function getKey($key)\n    {\n        return $this->getTenant() . ':' . $key;\n    }\n}\n```\n\n**Tenant-Aware Cache:**\n\n```php\nclass TenantCache\n{\n    public function remember($key, $ttl, $callback)\n    {\n        $tenantKey = $this->getTenantKey($key);\n        \n        return Cache::remember($tenantKey, $ttl, $callback);\n    }\n    \n    private function getTenantKey($key)\n    {\n        $tenant = app(TenantManager::class)->getTenant();\n        \n        return \"tenant:{$tenant}:{$key}\";\n    }\n}\n```\n\n**Tenant-Aware Queue:**\n\n```php\nclass TenantAwareJob implements ShouldQueue\n{\n    use SerializesModels;\n    \n    public $tenant;\n    \n    public function __construct()\n    {\n        $this->tenant = app(TenantManager::class)->getTenant();\n    }\n    \n    public function handle()\n    {\n        app(TenantManager::class)->setTenant($this->tenant);\n        \n        \u002F\u002F Job logic\n    }\n}\n```\n\n**Tenant Provisioning:**\n\n```php\nclass TenantProvisioner\n{\n    public function provision(Tenant $tenant)\n    {\n        \u002F\u002F Create database\n        DB::statement(\"CREATE DATABASE IF NOT EXISTS {$tenant->id}\");\n        \n        \u002F\u002F Run migrations\n        Artisan::call('migrate', [\n            '--database' => 'tenant',\n            '--path' => 'database\u002Fmigrations\u002Ftenant',\n            '--force' => true,\n        ]);\n        \n        \u002F\u002F Seed data\n        Artisan::call('db:seed', [\n            '--class' => 'TenantDatabaseSeeder',\n            '--force' => true,\n        ]);\n        \n        \u002F\u002F Configure domain\n        $this->configureDomain($tenant->domain);\n        \n        \u002F\u002F Create queue worker\n        $this->createQueueWorker($tenant);\n    }\n    \n    public function deprovision(Tenant $tenant)\n    {\n        \u002F\u002F Backup tenant data\n        $this->backupTenantData($tenant);\n        \n        \u002F\u002F Drop database\n        DB::statement(\"DROP DATABASE IF EXISTS {$tenant->id}\");\n        \n        \u002F\u002F Remove domain configuration\n        $this->removeDomainConfig($tenant->domain);\n    }\n}\n```\n\n**Tenant Migration Strategy:**\n\n```php\n\u002F\u002F database\u002Fmigrations\u002Ftenant\u002F2024_01_01_000001_create_tenant_posts_table.php\nclass CreateTenantPostsTable extends Migration\n{\n    public function up()\n    {\n        Schema::connection('tenant')->create('posts', function (Blueprint $table) {\n            $table->id();\n            $table->string('title');\n            $table->timestamps();\n        });\n    }\n}\n\n\u002F\u002F Run tenant migrations\nphp artisan migrate --database=tenant --path=database\u002Fmigrations\u002Ftenant\n```\n\n**Best Practices:**\n- Isolate tenant data completely\n- Use separate databases for sensitive tenants\n- Implement tenant-aware logging\n- Monitor tenant resource usage\n- Plan for tenant upgrades\n\n**Security Considerations:**\n- Validate tenant identifiers\n- Prevent tenant impersonation\n- Encrypt tenant database credentials\n- Implement rate limiting per tenant\n\n**Performance:**\n- Database-per-tenant offers best isolation but more connections\n- Single database with tenant column has lower overhead\n- Use connection pooling for database-per-tenant\n\n**Follow-up Questions:**\n- How do you handle cross-tenant reporting?\n- What's your backup strategy for multi-tenancy?\n- How do you migrate tenant schemas?",[441,442,443,20],"Multi-tenancy","SaaS","Isolation",{"id":445,"category":380,"question":446,"answer":447,"level":343,"tags":448},57,"How do you implement a GraphQL API in Laravel using Lighthouse?","GraphQL provides a flexible API where clients request exactly the data they need.\n\n**Installation:**\n\n```bash\ncomposer require nuwave\u002Flighthouse\nphp artisan lighthouse:install\nphp artisan vendor:publish --tag=lighthouse-schema\n```\n\n**Basic Schema (graphql\u002Fschema.graphql):**\n\n```graphql\ntype User {\n    id: ID!\n    name: String!\n    email: String!\n    posts: [Post!]! @hasMany\n    created_at: DateTime!\n}\n\ntype Post {\n    id: ID!\n    title: String!\n    content: String!\n    author: User! @belongsTo\n    comments: [Comment!]! @hasMany\n    published_at: DateTime\n}\n\ntype Comment {\n    id: ID!\n    content: String!\n    user: User! @belongsTo\n    post: Post! @belongsTo\n}\n\ntype Query {\n    users: [User!]! @all\n    user(id: ID! @eq): User @find\n    posts: [Post!]! @paginate\n    searchPosts(title: String! @where(operator: \"like\")): [Post!]! @all\n}\n\ntype Mutation {\n    createPost(input: CreatePostInput! @spread): Post! @create\n    updatePost(id: ID!, input: UpdatePostInput! @spread): Post! @update\n    deletePost(id: ID!): Post! @delete\n    addComment(input: AddCommentInput! @spread): Comment! @create\n}\n\ninput CreatePostInput {\n    title: String!\n    content: String!\n    author_id: ID!\n}\n\ninput UpdatePostInput {\n    title: String\n    content: String\n}\n\ninput AddCommentInput {\n    content: String!\n    post_id: ID!\n    user_id: ID!\n}\n```\n\n**Resolvers (Directives):**\n\n```php\n\u002F\u002F app\u002FGraphQL\u002FQueries\u002FUserPosts.php\nclass UserPosts\n{\n    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)\n    {\n        $user = User::find($args['user_id']);\n        \n        return $user->posts()\n            ->where('published', true)\n            ->latest()\n            ->get();\n    }\n}\n\n\u002F\u002F Schema\n\u002F\u002F postsByUser(user_id: ID!): [Post!]! @field(resolver: \"App\\\\GraphQL\\\\Queries\\\\UserPosts@__invoke\")\n```\n\n**Custom Resolver Class:**\n\n```php\nnamespace App\\GraphQL\\Queries;\n\nuse Closure;\nuse GraphQL\\Type\\Definition\\ResolveInfo;\nuse Nuwave\\Lighthouse\\Support\\Contracts\\GraphQLContext;\n\nclass StatsResolver\n{\n    public function resolve($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)\n    {\n        return [\n            'total_users' => User::count(),\n            'total_posts' => Post::count(),\n            'total_comments' => Comment::count(),\n        ];\n    }\n}\n\n\u002F\u002F Schema\ntype Stats {\n    total_users: Int!\n    total_posts: Int!\n    total_comments: Int!\n}\n\nextend type Query {\n    stats: Stats! @field(resolver: \"App\\\\GraphQL\\\\Queries\\\\StatsResolver@resolve\")\n}\n```\n\n**Complex Mutations:**\n\n```php\nnamespace App\\GraphQL\\Mutations;\n\nclass CreatePostWithAuthor\n{\n    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)\n    {\n        DB::beginTransaction();\n        \n        try {\n            $author = User::firstOrCreate(\n                ['email' => $args['author_email']],\n                ['name' => $args['author_name']]\n            );\n            \n            $post = Post::create([\n                'title' => $args['title'],\n                'content' => $args['content'],\n                'user_id' => $author->id,\n            ]);\n            \n            DB::commit();\n            \n            return $post;\n        } catch (\\Exception $e) {\n            DB::rollBack();\n            throw $e;\n        }\n    }\n}\n\n\u002F\u002F Schema\nextend type Mutation {\n    createPostWithAuthor(\n        title: String!\n        content: String!\n        author_email: String!\n        author_name: String!\n    ): Post! @field(resolver: \"App\\\\GraphQL\\\\Mutations\\\\CreatePostWithAuthor@__invoke\")\n}\n```\n\n**Validation:**\n\n```php\nnamespace App\\GraphQL\\Validators;\n\nuse Nuwave\\Lighthouse\\Validation\\Validator;\n\nclass CreatePostValidator extends Validator\n{\n    public function rules(): array\n    {\n        return [\n            'title' => ['required', 'string', 'max:255'],\n            'content' => ['required', 'string', 'min:10'],\n            'author_id' => ['required', 'exists:users,id'],\n        ];\n    }\n    \n    public function messages(): array\n    {\n        return [\n            'title.required' => 'A title is required',\n            'content.min' => 'Content must be at least 10 characters',\n        ];\n    }\n}\n\n\u002F\u002F Schema\ncreatePost(input: CreatePostInput! @spread): Post! @create @validate(validator: \"App\\\\GraphQL\\\\Validators\\\\CreatePostValidator\")\n```\n\n**Authentication and Authorization:**\n\n```php\n\u002F\u002F Schema directives\nextend type Query {\n    me: User! @auth\n    myPosts: [Post!]! @guard @hasMany(relation: \"posts\")\n}\n\n\u002F\u002F Custom authorization\nclass PostPolicy\n{\n    public function update($user, $post)\n    {\n        return $user->id === $post->user_id;\n    }\n}\n\n\u002F\u002F Schema\nupdatePost(id: ID!, input: UpdatePostInput!): Post! \n    @update \n    @can(ability: \"update\", find: \"id\")\n```\n\n**Pagination and Filtering:**\n\n```graphql\ntype Query {\n    # Pagination\n    posts: [Post!]! @paginate(builder: \"App\\\\GraphQL\\\\Builders\\\\PostBuilder@paginate\")\n    \n    # Custom pagination\n    recentPosts: [Post!]! @paginate(builder: \"App\\\\GraphQL\\\\Builders\\\\PostBuilder@recent\")\n}\n\n\u002F\u002F Builder class\nclass PostBuilder\n{\n    public function paginate($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)\n    {\n        return Post::with('author')\n            ->where('published', true)\n            ->orderBy('created_at', 'desc');\n    }\n    \n    public function recent($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)\n    {\n        return Post::where('created_at', '>=', now()->subDays(7));\n    }\n}\n```\n\n**Custom Directives:**\n\n```php\nnamespace App\\GraphQL\\Directives;\n\nuse Nuwave\\Lighthouse\\Schema\\Directives\\BaseDirective;\nuse Nuwave\\Lighthouse\\Support\\Contracts\\Directive;\n\nclass UpperCaseDirective extends BaseDirective implements Directive\n{\n    public static function definition(): string\n    {\n        return \u002F** @lang GraphQL *\u002F \u003C\u003C\u003C'GRAPHQL'\n\"\"\"\nConvert string field to uppercase\n\"\"\"\ndirective @upperCase on FIELD_DEFINITION\nGRAPHQL;\n    }\n    \n    public function handleField($field)\n    {\n        return function ($root) {\n            $value = $this->directiveArgValue('value') ?? $root->{$field->name};\n            \n            return strtoupper($value);\n        };\n    }\n}\n\n\u002F\u002F Usage\ntype User {\n    name: String! @upperCase\n}\n```\n\n**Performance Optimization:**\n\n```php\n\u002F\u002F config\u002Flighthouse.php\n'paginate' => [\n    'default_count' => 15,\n    'max_count' => 100,\n],\n\n'complexity' => [\n    'analysis' => true,\n    'default' => 1,\n    'fields' => [\n        'Query.users' => 5,\n        'Query.posts' => 10,\n    ],\n],\n\n\u002F\u002F Batch loading with DataLoader\nclass PostDataLoader\n{\n    public function load($userId)\n    {\n        return DataLoader::load('posts_by_user', $userId, function ($userIds) {\n            $posts = Post::whereIn('user_id', $userIds)->get();\n            \n            return $posts->groupBy('user_id');\n        });\n    }\n}\n```\n\n**Error Handling:**\n\n```php\nnamespace App\\GraphQL\\Errors;\n\nuse GraphQL\\Error\\ClientAware;\n\nclass ValidationError extends \\Exception implements ClientAware\n{\n    public function isClientSafe(): bool\n    {\n        return true;\n    }\n    \n    public function getCategory(): string\n    {\n        return 'validation';\n    }\n}\n\n\u002F\u002F In resolver\nif ($invalid) {\n    throw new ValidationError('Invalid input data');\n}\n```\n\n**Testing GraphQL:**\n\n```php\nclass GraphQLTest extends TestCase\n{\n    public function test_query_users()\n    {\n        $response = $this->graphQL('\n            query {\n                users {\n                    id\n                    name\n                    email\n                }\n            }\n        ');\n        \n        $response->assertJsonStructure([\n            'data' => [\n                'users' => [\n                    ['id', 'name', 'email']\n                ]\n            ]\n        ]);\n    }\n    \n    public function test_create_post_mutation()\n    {\n        $response = $this->graphQL('\n            mutation CreatePost($title: String!, $content: String!) {\n                createPost(title: $title, content: $content) {\n                    id\n                    title\n                    content\n                }\n            }\n        ', [\n            'title' => 'New Post',\n            'content' => 'Post content',\n        ]);\n        \n        $response->assertJsonPath('data.createPost.title', 'New Post');\n    }\n}\n```\n\n**Best Practices:**\n- Define clear schema first\n- Use DataLoader to prevent N+1\n- Implement query complexity analysis\n- Cache GraphQL responses\n- Version schema via namespaces\n\n**Follow-up Questions:**\n- How do you handle file uploads in GraphQL?\n- What's your strategy for schema evolution?\n- How do you monitor GraphQL performance?",[449,450,451,55],"GraphQL","Lighthouse","API",{"id":453,"category":380,"question":454,"answer":455,"level":343,"tags":456},58,"How do you implement serverless Laravel using Vapor?","Laravel Vapor deploys Laravel applications to AWS Lambda, providing auto-scaling serverless infrastructure.\n\n**Installation and Configuration:**\n\n```bash\ncomposer require laravel\u002Fvapor\nphp artisan vapor:install\n```\n\n**vapor.yml Configuration:**\n\n```yaml\n# vapor.yml\nid: 12345\nname: my-app\nevironment: production\n\nenvironments:\n  production:\n    domain: myapp.com\n    memory: 1024\n    cli-memory: 512\n    warm: 10\n    storage: my-app-storage\n    database: my-app-database\n    cache: my-app-cache\n    queue: my-app-queue\n    redis: my-app-redis\n    \n    # Environment variables\n    variables:\n      APP_ENV: production\n      APP_DEBUG: false\n      LOG_CHANNEL: stderr\n      SESSION_DRIVER: cookie\n      \n    # Secrets (from Vapor UI)\n    secrets:\n      - STRIPE_KEY\n      - STRIPE_SECRET\n      \n    # Scheduled tasks\n    schedules:\n      - command: inspire\n        expression: \"* * * * *\"\n        \n    # CloudFront CDN\n    cdn: true\n    \n    # Assets\n    assets:\n      - public\u002Fcss\n      - public\u002Fjs\n      - public\u002Fimages\n```\n\n**Deployment Commands:**\n\n```bash\n# Deploy to production\nvapor deploy production\n\n# Deploy with specific environment\nvapor deploy staging\n\n# List environments\nvapor list\n\n# Switch environment\nvapor switch production\n\n# Rollback to previous version\nvapor rollback production\n\n# View logs\nvapor logs production\n```\n\n**Database Connection:**\n\n```php\n\u002F\u002F config\u002Fdatabase.php\n'connections' => [\n    'mysql' => [\n        'driver' => 'mysql',\n        'url' => env('DATABASE_URL'), \u002F\u002F Vapor provides this\n        'host' => env('DB_HOST', '127.0.0.1'),\n        'port' => env('DB_PORT', '3306'),\n        'database' => env('DB_DATABASE', 'forge'),\n        'username' => env('DB_USERNAME', 'forge'),\n        'password' => env('DB_PASSWORD', ''),\n        'unix_socket' => env('DB_SOCKET', ''),\n        'charset' => 'utf8mb4',\n        'collation' => 'utf8mb4_unicode_ci',\n        'prefix' => '',\n        'strict' => true,\n        'engine' => null,\n    ],\n];\n```\n\n**Storage Configuration:**\n\n```php\n\u002F\u002F config\u002Ffilesystems.php\n'disks' => [\n    's3' => [\n        'driver' => 's3',\n        'key' => env('AWS_ACCESS_KEY_ID'),\n        'secret' => env('AWS_SECRET_ACCESS_KEY'),\n        'region' => env('AWS_DEFAULT_REGION'),\n        'bucket' => env('AWS_BUCKET'),\n        'url' => env('AWS_URL'),\n        'endpoint' => env('AWS_ENDPOINT'),\n        'use_path_style_endpoint' => false,\n    ],\n],\n\n\u002F\u002F Vapor automatically uses S3 for file storage\nStorage::disk('s3')->put('file.txt', 'content');\n```\n\n**Queue Configuration:**\n\n```php\n\u002F\u002F config\u002Fqueue.php\n'connections' => [\n    'sqs' => [\n        'driver' => 'sqs',\n        'key' => env('AWS_ACCESS_KEY_ID'),\n        'secret' => env('AWS_SECRET_ACCESS_KEY'),\n        'prefix' => env('SQS_PREFIX', 'https:\u002F\u002Fsqs.us-east-1.amazonaws.com\u002Fyour-account-id'),\n        'queue' => env('SQS_QUEUE', 'default'),\n        'suffix' => env('SQS_SUFFIX'),\n        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),\n    ],\n],\n\n\u002F\u002F Vapor automatically uses SQS\nProcessPodcast::dispatch()->onQueue('high');\n```\n\n**Cache Configuration:**\n\n```php\n\u002F\u002F config\u002Fcache.php\n'default' => env('CACHE_DRIVER', 'redis'),\n\n'stores' => [\n    'redis' => [\n        'driver' => 'redis',\n        'connection' => 'cache',\n        'lock_connection' => 'default',\n    ],\n],\n\n\u002F\u002F Vapor provides ElastiCache Redis\nCache::remember('key', 3600, fn() => expensiveOperation());\n```\n\n**Environment-Aware Code:**\n\n```php\n\u002F\u002F Detect Vapor environment\nif (isset($_ENV['VAPOR'])) {\n    \u002F\u002F Running on Vapor\n}\n\n\u002F\u002F Vapor-specific helpers\nif (Vapor::isRunningOnVapor()) {\n    \u002F\u002F Serverless environment\n}\n\n\u002F\u002F Session configuration\n\u002F\u002F Vapor recommends cookie driver for sessions\nSESSION_DRIVER=cookie\n\n\u002F\u002F Logging to CloudWatch\nLOG_CHANNEL=stderr\n```\n\n**Handling File Uploads:**\n\n```php\n\u002F\u002F Vapor automatically handles file uploads via S3 presigned URLs\npublic function upload(Request $request)\n{\n    $request->validate([\n        'photo' => 'required|image|max:10240',\n    ]);\n    \n    \u002F\u002F File is automatically streamed to S3\n    $path = $request->file('photo')->store('photos', 's3');\n    \n    return response()->json(['path' => $path]);\n}\n\n\u002F\u002F Generate temporary URL for private files\n$url = Storage::disk('s3')->temporaryUrl(\n    'file.pdf', now()->addMinutes(5)\n);\n```\n\n**Warming Lambdas (Cold Start Mitigation):**\n\n```yaml\n# vapor.yml\nenvironments:\n  production:\n    warm: 10  # Keep 10 Lambdas warm\n    \n    # Keep specific routes warm\n    warm-extra:\n      - \u002Fapi\u002Fhealth\n      - \u002Fapi\u002Fpopular-posts\n```\n\n**Custom Domains and SSL:**\n\n```yaml\n# vapor.yml\nenvironments:\n  production:\n    domain: myapp.com\n    \n    # Additional domains\n    domains:\n      - www.myapp.com\n      - api.myapp.com\n```\n\n**Database Migrations:**\n\n```bash\n# Run migrations on production\nvapor migrate production\n\n# With seeders\nvapor migrate production --seed\n\n# Rollback\nvapor migrate production --rollback\n```\n\n**Asset Handling:**\n\n```php\n\u002F\u002F Versioned assets\nmix.js('resources\u002Fjs\u002Fapp.js', 'public\u002Fjs')\n   .version();\n\n\u002F\u002F In views\n\u003Clink rel=\"stylesheet\" href=\"{{ mix('css\u002Fapp.css') }}\">\n\u003Cscript src=\"{{ mix('js\u002Fapp.js') }}\" defer>\u003C\u002Fscript>\n\n\u002F\u002F CDN URLs\n\u003Cimg src=\"{{ asset('images\u002Flogo.png') }}\">\n```\n\n**Security Best Practices:**\n\n```php\n\u002F\u002F Use secrets for sensitive data\n\u002F\u002F In Vapor UI, add secrets like STRIPE_KEY, STRIPE_SECRET\n\n\u002F\u002F Access secrets via environment\n$key = env('STRIPE_KEY');\n\n\u002F\u002F Database security\n\u002F\u002F Vapor uses AWS RDS Proxy for connection pooling\n\u002F\u002F Enable automated backups\n\n\u002F\u002F Enable WAF\n\u002F\u002F In Vapor UI, enable AWS WAF\n```\n\n**Monitoring and Logging:**\n\n```php\n\u002F\u002F CloudWatch logs automatically collected\nLog::info('User action', ['user_id' => auth()->id()]);\n\n\u002F\u002F Vapor metrics\n\u002F\u002F View in Vapor UI or CloudWatch\n\u002F\u002F - Lambda invocations\n\u002F\u002F - Duration\n\u002F\u002F - Errors\n\u002F\u002F - Memory usage\n\n\u002F\u002F Custom metrics\nVapor::metrics([\n    'users_created' => 5,\n    'orders_processed' => 10,\n]);\n```\n\n**Performance Optimization:**\n\n```php\n\u002F\u002F Increase memory for CPU-intensive tasks\n\u002F\u002F vapor.yml\nmemory: 2048\n\n\u002F\u002F Use Lambda layers for dependencies\n\u002F\u002F vapor.yml\nlayers:\n  - arn:aws:lambda:us-east-1:123456789:layer:gd:1\n\n\u002F\u002F Optimize autoloader\ncomposer install --optimize-autoloader --no-dev\n```\n\n**Limitations and Considerations:**\n\n```php\n\u002F\u002F 1. Execution time limit (900 seconds max)\nset_time_limit(900);\n\n\u002F\u002F 2. Temporary storage (512MB - 10GB)\n$tempPath = sys_get_temp_dir() . '\u002Ffile.txt';\n\n\u002F\u002F 3. No persistent connections\n\u002F\u002F Database connections are re-established per invocation\n\n\u002F\u002F 4. WebSockets not supported\n\u002F\u002F Use polling or AWS IoT Core\n\n\u002F\u002F 5. Custom binaries require Lambda layers\n```\n\n**Cost Optimization:**\n\n```yaml\n# vapor.yml\nenvironments:\n  production:\n    memory: 1024  # Balanced\n    warm: 5       # Reduce warm instances\n    \n    # Provisioned concurrency for predictable traffic\n    provisioned-concurrency:\n      - path: \u002Fapi\u002Fcheckout\n        concurrency: 10\n```\n\n**Best Practices:**\n- Use cookie sessions for statelessness\n- Implement idempotency keys for mutations\n- Set appropriate Lambda memory (more memory = faster CPU)\n- Use CloudFront for CDN\n- Monitor cold starts\n\n**Follow-up Questions:**\n- How do you handle WebSocket connections on Vapor?\n- What's your strategy for database connection management?\n- How do you debug Lambda failures in production?",[457,458,459,460],"Vapor","Serverless","AWS Lambda","Cloud",{"id":462,"category":380,"question":463,"answer":464,"level":343,"tags":465},59,"How do you implement OAuth2 authentication with Laravel Passport?","Passport provides a full OAuth2 server for API authentication with multiple grant types.\n\n**Installation:**\n\n```bash\ncomposer require laravel\u002Fpassport\nphp artisan passport:install\nphp artisan migrate\n```\n\n**Configuration:**\n\n```php\n\u002F\u002F User model\nuse Laravel\\Passport\\HasApiTokens;\n\nclass User extends Authenticatable\n{\n    use HasApiTokens, HasFactory, Notifiable;\n}\n\n\u002F\u002F AuthServiceProvider\nuse Laravel\\Passport\\Passport;\n\npublic function boot()\n{\n    Passport::routes();\n    \n    \u002F\u002F Token expiration\n    Passport::tokensExpireIn(now()->addDays(15));\n    Passport::refreshTokensExpireIn(now()->addDays(30));\n    Passport::personalAccessTokensExpireIn(now()->addMonths(6));\n    \n    \u002F\u002F Token scopes\n    Passport::tokensCan([\n        'read-posts' => 'Read posts',\n        'write-posts' => 'Create and edit posts',\n        'delete-posts' => 'Delete posts',\n        'admin' => 'Perform administrative actions',\n    ]);\n    \n    \u002F\u002F Default scope\n    Passport::setDefaultScope([\n        'read-posts',\n    ]);\n}\n\n\u002F\u002F config\u002Fauth.php\n'guards' => [\n    'api' => [\n        'driver' => 'passport',\n        'provider' => 'users',\n    ],\n],\n```\n\n**Password Grant (First-party client):**\n\n```php\n\u002F\u002F Create password grant client\nphp artisan passport:client --password\n\n\u002F\u002F Login endpoint\npublic function login(Request $request)\n{\n    $request->validate([\n        'email' => 'required|email',\n        'password' => 'required',\n    ]);\n    \n    $client = Client::where('password_client', true)->first();\n    \n    $response = Http::asForm()->post(env('APP_URL') . '\u002Foauth\u002Ftoken', [\n        'grant_type' => 'password',\n        'client_id' => $client->id,\n        'client_secret' => $client->secret,\n        'username' => $request->email,\n        'password' => $request->password,\n        'scope' => '',\n    ]);\n    \n    return $response->json();\n}\n\n\u002F\u002F Refresh token\npublic function refresh(Request $request)\n{\n    $client = Client::where('password_client', true)->first();\n    \n    $response = Http::asForm()->post(env('APP_URL') . '\u002Foauth\u002Ftoken', [\n        'grant_type' => 'refresh_token',\n        'refresh_token' => $request->refresh_token,\n        'client_id' => $client->id,\n        'client_secret' => $client->secret,\n        'scope' => '',\n    ]);\n    \n    return $response->json();\n}\n\n\u002F\u002F Logout (revoke token)\npublic function logout(Request $request)\n{\n    $request->user()->token()->revoke();\n    \n    return response()->json(['message' => 'Logged out']);\n}\n```\n\n**Authorization Code Grant (Third-party clients):**\n\n```php\n\u002F\u002F Create auth code client\nphp artisan passport:client\n\n\u002F\u002F Redirect to authorization endpoint\n\u002F\u002F GET \u002Foauth\u002Fauthorize?client_id=client-id&redirect_uri=http:\u002F\u002Fexample.com\u002Fcallback&response_type=code&scope=read-posts\n\n\u002F\u002F Callback to exchange code for token\npublic function callback(Request $request)\n{\n    $client = Client::find($request->client_id);\n    \n    $response = Http::asForm()->post(env('APP_URL') . '\u002Foauth\u002Ftoken', [\n        'grant_type' => 'authorization_code',\n        'client_id' => $client->id,\n        'client_secret' => $client->secret,\n        'redirect_uri' => $client->redirect,\n        'code' => $request->code,\n    ]);\n    \n    return $response->json();\n}\n```\n\n**Personal Access Tokens (User-generated):**\n\n```php\n\u002F\u002F Create token\npublic function createToken(Request $request)\n{\n    $token = $request->user()->createToken(\n        'MyApp', ['read-posts', 'write-posts']\n    )->accessToken;\n    \n    return response()->json(['token' => $token]);\n}\n\n\u002F\u002F Revoke token\npublic function revokeToken(Request $request, $tokenId)\n{\n    $request->user()->tokens()->where('id', $tokenId)->delete();\n    \n    return response()->json(['message' => 'Token revoked']);\n}\n\n\u002F\u002F List tokens\npublic function listTokens(Request $request)\n{\n    return response()->json($request->user()->tokens);\n}\n```\n\n**Token Scopes (Permissions):**\n\n```php\n\u002F\u002F Assign scopes when creating token\n$token = $user->createToken('MyToken', ['read-posts'])->accessToken;\n\n\u002F\u002F Check scopes in controller\npublic function update(Post $post)\n{\n    if ($request->user()->tokenCan('write-posts')) {\n        \u002F\u002F User can write posts\n    }\n}\n\n\u002F\u002F Middleware for scopes\nRoute::post('\u002Fposts', function () {\n    \u002F\u002F\n})->middleware('scope:write-posts');\n\n\u002F\u002F Check multiple scopes\nRoute::get('\u002Fadmin', function () {\n    \u002F\u002F\n})->middleware('scopes:admin,write-posts');\n```\n\n**Client Credentials Grant (Machine-to-machine):**\n\n```php\n\u002F\u002F Create client credentials client\nphp artisan passport:client --client\n\n\u002F\u002F Get token\n$response = Http::asForm()->post(env('APP_URL') . '\u002Foauth\u002Ftoken', [\n    'grant_type' => 'client_credentials',\n    'client_id' => $client->id,\n    'client_secret' => $client->secret,\n    'scope' => 'admin',\n]);\n\n\u002F\u002F Authenticate\nRoute::middleware('client')->get('\u002Fsystem-status', function () {\n    \u002F\u002F Client authenticated\n});\n```\n\n**Customizing Passport:**\n\n```php\n\u002F\u002F Custom token model\nuse Laravel\\Passport\\Token;\n\nclass CustomToken extends Token\n{\n    \u002F\u002F Add custom methods\n}\n\n\u002F\u002F In AuthServiceProvider\nPassport::useTokenModel(CustomToken::class);\n\n\u002F\u002F Custom client model\nuse Laravel\\Passport\\Client;\n\nclass CustomClient extends Client\n{\n    \u002F\u002F Add custom methods\n}\n\nPassport::useClientModel(CustomClient::class);\n\n\u002F\u002F Custom guard\npublic function boot()\n{\n    Passport::viaRequest('custom', function ($request) {\n        $token = $request->bearerToken();\n        \n        return User::where('api_token', $token)->first();\n    });\n}\n```\n\n**API Routes Protection:**\n\n```php\n\u002F\u002F routes\u002Fapi.php\nRoute::middleware('auth:api')->group(function () {\n    Route::get('\u002Fuser', function (Request $request) {\n        return $request->user();\n    });\n    \n    Route::get('\u002Fposts', [PostController::class, 'index']);\n    Route::post('\u002Fposts', [PostController::class, 'store'])\n        ->middleware('scope:write-posts');\n});\n```\n\n**Testing Passport:**\n\n```php\nuse Laravel\\Passport\\Passport;\n\nclass PostTest extends TestCase\n{\n    public function test_authenticated_user_can_view_posts()\n    {\n        $user = User::factory()->create();\n        \n        Passport::actingAs($user, ['read-posts']);\n        \n        $response = $this->getJson('\u002Fapi\u002Fposts');\n        \n        $response->assertStatus(200);\n    }\n    \n    public function test_user_without_scope_cannot_create_post()\n    {\n        $user = User::factory()->create();\n        \n        Passport::actingAs($user, ['read-posts']);\n        \n        $response = $this->postJson('\u002Fapi\u002Fposts', [...]);\n        \n        $response->assertStatus(403);\n    }\n}\n```\n\n**Security Best Practices:**\n- Store client secrets securely\n- Use HTTPS in production\n- Implement token revocation\n- Rotate client secrets periodically\n- Limit token scopes\n- Set appropriate token lifetimes\n\n**Performance Considerations:**\n- Passport adds middleware overhead\n- Use token caching for high-traffic APIs\n- Consider using Sanctum for simpler use cases\n\n**Common Issues:**\n- Token revocation not working (check database indexes)\n- Scope validation failing (verify middleware order)\n- Client not found (check client type)\n\n**Follow-up Questions:**\n- How do you implement social login with Passport?\n- What's the difference between Passport and Sanctum?\n- How do you handle token revocation on password change?",[186,466,79,467],"OAuth2","API Security",{"id":469,"category":380,"question":470,"answer":471,"level":343,"tags":472},60,"How do you implement a microservices architecture with Laravel?","Microservices architecture decomposes an application into small, independent services communicating via APIs or message brokers.\n\n**Service Discovery with Consul:**\n\n```php\n\u002F\u002F Service registration\nclass ServiceRegistry\n{\n    public function register($serviceName, $host, $port)\n    {\n        $client = new Consul\\Client();\n        \n        $client->put('v1\u002Fagent\u002Fservice\u002Fregister', [\n            'body' => json_encode([\n                'Name' => $serviceName,\n                'Address' => $host,\n                'Port' => $port,\n                'Check' => [\n                    'HTTP' => \"http:\u002F\u002F{$host}:{$port}\u002Fhealth\",\n                    'Interval' => '10s',\n                ],\n            ]),\n        ]);\n    }\n    \n    public function discover($serviceName)\n    {\n        $client = new Consul\\Client();\n        \n        $response = $client->get(\"v1\u002Fhealth\u002Fservice\u002F{$serviceName}\");\n        $services = json_decode($response->getBody(), true);\n        \n        return collect($services)\n            ->filter(fn($s) => $s['Checks'][0]['Status'] === 'passing')\n            ->map(fn($s) => $s['Service']);\n    }\n}\n\n\u002F\u002F Service provider\nclass ConsulServiceProvider extends ServiceProvider\n{\n    public function boot()\n    {\n        $this->app->booted(function () {\n            $registry = app(ServiceRegistry::class);\n            \n            $registry->register(\n                config('app.name'),\n                gethostname(),\n                env('APP_PORT', 80)\n            );\n        });\n    }\n}\n```\n\n**HTTP Client for Service Communication:**\n\n```php\nclass ServiceClient\n{\n    private $retryCount = 3;\n    private $timeout = 30;\n    \n    public function call($service, $endpoint, $method = 'GET', $data = [])\n    {\n        $services = app(ServiceRegistry::class)->discover($service);\n        \n        if ($services->isEmpty()) {\n            throw new ServiceUnavailableException(\"No instances of {$service} available\");\n        }\n        \n        \u002F\u002F Load balancing (round-robin)\n        $serviceInstance = $services->random();\n        $url = \"http:\u002F\u002F{$serviceInstance['Address']}:{$serviceInstance['Port']}\u002F{$endpoint}\";\n        \n        return retry($this->retryCount, function () use ($url, $method, $data) {\n            $response = Http::timeout($this->timeout)->$method($url, $data);\n            \n            if (!$response->successful()) {\n                throw new ServiceCallException(\"Service returned {$response->status()}\");\n            }\n            \n            return $response->json();\n        }, 100); \u002F\u002F 100ms delay between retries\n    }\n}\n\n\u002F\u002F Usage in controller\nclass OrderController extends Controller\n{\n    public function store(Request $request, ServiceClient $client)\n    {\n        \u002F\u002F Call inventory service\n        $inventory = $client->call('inventory-service', 'api\u002Fcheck', 'POST', [\n            'items' => $request->items\n        ]);\n        \n        \u002F\u002F Call payment service\n        $payment = $client->call('payment-service', 'api\u002Fcharge', 'POST', [\n            'amount' => $request->total,\n            'method' => $request->payment_method\n        ]);\n        \n        \u002F\u002F Create order\n        $order = Order::create([...]);\n        \n        \u002F\u002F Call notification service (async)\n        dispatch(new SendOrderNotification($order));\n        \n        return response()->json($order, 201);\n    }\n}\n```\n\n**Message Broker for Async Communication (RabbitMQ):**\n\n```php\n\u002F\u002F Event publishing\nclass EventPublisher\n{\n    public function publish($event, $data, $routingKey)\n    {\n        $connection = new AMQPStreamConnection(\n            config('rabbitmq.host'),\n            config('rabbitmq.port'),\n            config('rabbitmq.user'),\n            config('rabbitmq.password')\n        );\n        \n        $channel = $connection->channel();\n        $channel->exchange_declare('events', 'topic', false, true, false);\n        \n        $message = new AMQPMessage(json_encode([\n            'event' => $event,\n            'data' => $data,\n            'timestamp' => now()->toIso8601String(),\n            'correlation_id' => (string) Str::uuid(),\n        ]));\n        \n        $channel->basic_publish($message, 'events', $routingKey);\n        \n        $channel->close();\n        $connection->close();\n    }\n}\n\n\u002F\u002F Event consumption\nclass EventConsumer\n{\n    public function consume($queue, $callback)\n    {\n        $connection = new AMQPStreamConnection(\n            config('rabbitmq.host'),\n            config('rabbitmq.port'),\n            config('rabbitmq.user'),\n            config('rabbitmq.password')\n        );\n        \n        $channel = $connection->channel();\n        $channel->exchange_declare('events', 'topic', false, true, false);\n        $channel->queue_declare($queue, false, true, false, false);\n        $channel->queue_bind($queue, 'events', $queue);\n        \n        $channel->basic_consume($queue, '', false, false, false, false, function ($message) use ($callback) {\n            $callback(json_decode($message->body, true));\n            $message->ack();\n        });\n        \n        while ($channel->is_consuming()) {\n            $channel->wait();\n        }\n    }\n}\n\n\u002F\u002F In order service (publisher)\n$publisher = app(EventPublisher::class);\n$publisher->publish('order.placed', [\n    'order_id' => $order->id,\n    'user_id' => $order->user_id,\n    'total' => $order->total,\n], 'order.placed');\n\n\u002F\u002F In inventory service (consumer)\n$consumer = app(EventConsumer::class);\n$consumer->consume('order.placed', function ($event) {\n    \u002F\u002F Update inventory\n    foreach ($event['data']['items'] as $item) {\n        Inventory::where('product_id', $item['id'])->decrement('stock', $item['quantity']);\n    }\n});\n```\n\n**API Gateway Pattern:**\n\n```php\nclass ApiGateway\n{\n    private $routes = [\n        'users' => 'user-service',\n        'orders' => 'order-service',\n        'products' => 'product-service',\n        'payments' => 'payment-service',\n    ];\n    \n    public function route($request)\n    {\n        $path = $request->path();\n        $segments = explode('\u002F', $path);\n        \n        if (isset($segments[0]) && isset($this->routes[$segments[0]])) {\n            $service = $this->routes[$segments[0]];\n            $endpoint = implode('\u002F', array_slice($segments, 1));\n            \n            return app(ServiceClient::class)->call(\n                $service,\n                $endpoint,\n                $request->method(),\n                $request->all()\n            );\n        }\n        \n        abort(404);\n    }\n}\n\n\u002F\u002F routes\u002Fweb.php\nRoute::any('\u002F{any}', function (Request $request) {\n    return app(ApiGateway::class)->route($request);\n})->where('any', '.*');\n```\n\n**Circuit Breaker Pattern:**\n\n```php\nclass CircuitBreaker\n{\n    private $failureCount = 0;\n    private $lastFailureTime = null;\n    private $state = 'closed'; \u002F\u002F closed, open, half-open\n    private $failureThreshold = 5;\n    private $timeout = 60; \u002F\u002F seconds\n    \n    public function call($service, $callback)\n    {\n        if ($this->state === 'open') {\n            if (time() - $this->lastFailureTime > $this->timeout) {\n                $this->state = 'half-open';\n            } else {\n                throw new CircuitOpenException(\"Circuit is open for {$service}\");\n            }\n        }\n        \n        try {\n            $result = $callback();\n            \n            if ($this->state === 'half-open') {\n                $this->reset();\n            }\n            \n            return $result;\n        } catch (\\Exception $e) {\n            $this->recordFailure();\n            throw $e;\n        }\n    }\n    \n    private function recordFailure()\n    {\n        $this->failureCount++;\n        $this->lastFailureTime = time();\n        \n        if ($this->failureCount >= $this->failureThreshold) {\n            $this->state = 'open';\n        }\n    }\n    \n    private function reset()\n    {\n        $this->failureCount = 0;\n        $this->state = 'closed';\n    }\n}\n\n\u002F\u002F Usage\n$breaker = app(CircuitBreaker::class);\n$result = $breaker->call('payment-service', function () use ($client) {\n    return $client->call('payment-service', 'api\u002Fcharge', 'POST', $data);\n});\n```\n\n**Distributed Tracing (OpenTelemetry):**\n\n```php\nclass TraceMiddleware\n{\n    public function handle($request, $next)\n    {\n        $traceId = $request->header('X-Trace-Id') ?? (string) Str::uuid();\n        \n        \u002F\u002F Store in context\n        Context::set('trace_id', $traceId);\n        \n        $startTime = microtime(true);\n        \n        $response = $next($request);\n        \n        $duration = microtime(true) - $startTime;\n        \n        \u002F\u002F Send to tracing system (Jaeger, Zipkin)\n        $this->sendTrace([\n            'trace_id' => $traceId,\n            'service' => config('app.name'),\n            'endpoint' => $request->path(),\n            'duration' => $duration,\n            'status' => $response->getStatusCode(),\n        ]);\n        \n        $response->header('X-Trace-Id', $traceId);\n        \n        return $response;\n    }\n}\n\n\u002F\u002F Propagate trace to downstream services\nclass ServiceClient\n{\n    public function call($service, $endpoint, $method = 'GET', $data = [])\n    {\n        $traceId = Context::get('trace_id');\n        \n        $response = Http::withHeaders([\n            'X-Trace-Id' => $traceId,\n        ])->$method($url, $data);\n        \n        return $response->json();\n    }\n}\n```\n\n**Saga Pattern for Distributed Transactions:**\n\n```php\nclass SagaOrchestrator\n{\n    private $steps = [];\n    private $compensations = [];\n    \n    public function addStep($name, $action, $compensation)\n    {\n        $this->steps[$name] = $action;\n        $this->compensations[$name] = $compensation;\n        \n        return $this;\n    }\n    \n    public function execute()\n    {\n        $executed = [];\n        \n        try {\n            foreach ($this->steps as $name => $action) {\n                $action();\n                $executed[] = $name;\n            }\n        } catch (\\Exception $e) {\n            \u002F\u002F Rollback in reverse order\n            foreach (array_reverse($executed) as $name) {\n                $this->compensations[$name]();\n            }\n            \n            throw $e;\n        }\n    }\n}\n\n\u002F\u002F Usage\n$saga = new SagaOrchestrator();\n\n$saga->addStep(\n    'reserve_inventory',\n    fn() => $client->call('inventory-service', 'api\u002Freserve', 'POST', $items),\n    fn() => $client->call('inventory-service', 'api\u002Frelease', 'POST', $items)\n);\n\n$saga->addStep(\n    'charge_payment',\n    fn() => $client->call('payment-service', 'api\u002Fcharge', 'POST', $payment),\n    fn() => $client->call('payment-service', 'api\u002Frefund', 'POST', $payment)\n);\n\n$saga->addStep(\n    'create_order',\n    fn() => Order::create([...]),\n    fn() => Order::where('id', $orderId)->delete()\n);\n\n$saga->execute();\n```\n\n**Configuration Management:**\n\n```php\n\u002F\u002F Use environment-specific configs\n\u002F\u002F config\u002Fservices.php\nreturn [\n    'user-service' => env('USER_SERVICE_URL', 'http:\u002F\u002Fuser-service'),\n    'order-service' => env('ORDER_SERVICE_URL', 'http:\u002F\u002Forder-service'),\n];\n\n\u002F\u002F Kubernetes ConfigMap\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: app-config\ndata:\n  .env: |\n    USER_SERVICE_URL=http:\u002F\u002Fuser-service.default.svc.cluster.local\n    ORDER_SERVICE_URL=http:\u002F\u002Forder-service.default.svc.cluster.local\n```\n\n**Best Practices:**\n- Design services around business capabilities\n- Use asynchronous communication when possible\n- Implement idempotency for all operations\n- Centralize logging and monitoring\n- Use API versioning\n- Implement health checks\n\n**Challenges:**\n- Distributed transactions\n- Service discovery\n- Data consistency\n- Network latency\n- Debugging complexity\n\n**Follow-up Questions:**\n- How do you handle database per service pattern?\n- What's your strategy for service versioning?\n- How do you test microservices locally?",[417,473,474,415],"Distributed Systems","Service Discovery",1779734544541]