debug:laravel
Debug Laravel applications systematically with this comprehensive troubleshooting skill. Covers class/namespace errors, database SQLSTATE issues, route problems (404/405), Blade template errors, middleware issues (CSRF/auth), queue job failures, and cache/session problems. Provides structured four-phase debugging methodology with Laravel Telescope, Debugbar, Artisan tinker, and logging best practices for development and production environments.
What this skill does
# Laravel Debugging Guide
## Overview
Debugging in Laravel requires understanding the framework's conventions, lifecycle, and tooling ecosystem. This guide provides a systematic approach to diagnosing and resolving Laravel issues, from simple configuration problems to complex runtime errors.
**Key Principles:**
- Always check logs first (`storage/logs/laravel.log`)
- Use appropriate tools for the environment (development vs production)
- Follow Laravel conventions - most errors stem from convention violations
- Isolate the problem layer (routing, middleware, controller, model, view)
## Common Error Patterns
### Class and Namespace Errors
**Class 'App\Http\Controllers\Controller' not found**
```php
// Problem: Missing base controller extension or incorrect namespace
// Solution: Ensure proper namespace and inheritance
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
class YourController extends BaseController
{
// ...
}
```
**Target class [ControllerName] does not exist**
```php
// Check routes/web.php or routes/api.php
// Laravel 8+ requires full namespace or route groups
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
// Or use route group with namespace
Route::namespace('App\Http\Controllers')->group(function () {
Route::get('/users', 'UserController@index');
});
```
### Database Errors (SQLSTATE)
**SQLSTATE[HY000] [1045] Access denied**
```bash
# Check .env database credentials
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
# Clear config cache after changes
php artisan config:clear
```
**SQLSTATE[42S02] Table not found**
```bash
# Run migrations
php artisan migrate
# Check migration status
php artisan migrate:status
# Fresh database with seeders
php artisan migrate:fresh --seed
```
**QueryException with foreign key constraint**
```php
// Check migration order - parent tables must exist first
// Use Schema::disableForeignKeyConstraints() for fresh migrations
Schema::disableForeignKeyConstraints();
// ... your schema changes
Schema::enableForeignKeyConstraints();
```
### Route Errors
**404 Not Found - Route does not exist**
```bash
# List all registered routes
php artisan route:list
# Check specific route
php artisan route:list --name=users
# Clear route cache
php artisan route:clear
```
**MethodNotAllowedHttpException**
```php
// Wrong HTTP method for route
// Check route definition matches request method
Route::post('/submit', [FormController::class, 'store']); // Expects POST
Route::put('/update/{id}', [FormController::class, 'update']); // Expects PUT
// For HTML forms using PUT/PATCH/DELETE
<form method="POST" action="/update/1">
@csrf
@method('PUT')
</form>
```
### View Errors
**View [name] not found**
```bash
# Check view file exists at correct path
# resources/views/users/index.blade.php for view('users.index')
# Clear view cache
php artisan view:clear
```
**Undefined variable in view**
```php
// Ensure variable is passed from controller
return view('users.index', [
'users' => $users,
'total' => $total,
]);
// Or use compact()
return view('users.index', compact('users', 'total'));
```
### Middleware Issues
**TokenMismatchException (CSRF)**
```php
// Include @csrf in all POST/PUT/DELETE forms
<form method="POST" action="/submit">
@csrf
<!-- form fields -->
</form>
// For AJAX requests, include token in headers
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Exclude routes from CSRF if needed (VerifyCsrfToken middleware)
protected $except = [
'stripe/*',
'webhook/*',
];
```
**Unauthenticated / 403 Forbidden**
```bash
# Check middleware applied to route
php artisan route:list --columns=uri,middleware
# Verify auth guards in config/auth.php
# Check Gate/Policy definitions
```
### Queue and Job Failures
**Job failed without reason**
```bash
# Check failed jobs table
php artisan queue:failed
# Retry specific job
php artisan queue:retry <job-id>
# Retry all failed jobs
php artisan queue:retry all
# Clear failed jobs
php artisan queue:flush
```
**Jobs not processing**
```bash
# Ensure queue worker is running
php artisan queue:work
# Check queue connection in .env
QUEUE_CONNECTION=redis
# Restart queue after code changes
php artisan queue:restart
```
### Cache and Session Problems
**Session not persisting**
```bash
# Clear session files
php artisan session:clear
# Check session driver
SESSION_DRIVER=file # or redis, database, etc.
# Verify storage permissions
chmod -R 775 storage/
chown -R www-data:www-data storage/
```
**Config/cache showing old values**
```bash
# Clear all caches
php artisan optimize:clear
# Or individually
php artisan config:clear
php artisan cache:clear
php artisan route:clear
php artisan view:clear
```
## Debugging Tools
### Laravel Telescope
The most comprehensive debugging tool for Laravel development.
**Installation:**
```bash
composer require laravel/telescope --dev
php artisan telescope:install
php artisan migrate
```
**Access:** Navigate to `/telescope` in your browser
**Key Features:**
- **Requests**: View all HTTP requests with headers, parameters, response
- **Exceptions**: Stack traces and context for all errors
- **Queries**: All SQL queries with execution time and bindings
- **Jobs**: Queue job payloads, execution times, failures
- **Logs**: All log entries in real-time
- **Mail**: Preview sent emails with content
- **Cache**: Track cache hits, misses, and operations
- **Events**: All dispatched events and listeners
**Security:** Limit access in production via `TelescopeServiceProvider`:
```php
protected function gate()
{
Gate::define('viewTelescope', function ($user) {
return in_array($user->email, [
'[email protected]',
]);
});
}
```
### Laravel Debugbar
Quick inline debugging for web pages.
**Installation:**
```bash
composer require barryvdh/laravel-debugbar --dev
```
**Features:**
- Query count and execution time
- Route information
- View rendering time
- Memory usage
- Timeline visualization
### Ray by Spatie
Desktop app for non-intrusive debugging.
**Installation:**
```bash
composer require spatie/laravel-ray --dev
```
**Usage:**
```php
ray($variable); // Send to Ray app
ray($var1, $var2)->green(); // Color coded
ray()->measure(); // Start timer
ray()->pause(); // Pause execution
ray()->showQueries(); // Show all queries
```
### Built-in Debugging Functions
```php
// Dump and Die - stops execution
dd($variable);
dd($user, $posts, $comments);
// Dump without dying
dump($variable);
// Dump, Die, Debug (with extra info)
ddd($variable);
// In Blade templates
@dd($variable)
@dump($variable)
// Log to file
Log::debug('Message', ['context' => $data]);
Log::info('User logged in', ['user_id' => $user->id]);
Log::error('Payment failed', ['order' => $order]);
// Log levels: emergency, alert, critical, error, warning, notice, info, debug
```
### Artisan Tinker
Interactive REPL for testing code:
```bash
php artisan tinker
# Test Eloquent queries
>>> User::where('active', true)->count()
=> 42
# Test relationships
>>> $user = User::find(1)
>>> $user->posts()->count()
# Test services
>>> app(UserService::class)->processUser($user)
```
## The Four Phases of Laravel Debugging
### Phase 1: Root Cause Investigation
**Check Logs First:**
```bash
# View latest errors
tail -f storage/logs/laravel.log
# Search for specific errors
grep -i "error\|exception" storage/logs/laravel.log | tail -50
# Check with specific date
cat storage/logs/laravel-2025-01-11.log
```
**Verify Configuration:**
```bash
# Check current environment
php artisan env
# Dump all config values
php artisan config:show
# Check specific config
php artisan config:show database
php artisan config:show queueRelated in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.