| name | debug:laravel |
| description | 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. |
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
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
class YourController extends BaseController
{
}
Target class [ControllerName] does not exist
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
Route::namespace('App\Http\Controllers')->group(function () {
Route::get('/users', 'UserController@index');
});
Database Errors (SQLSTATE)
SQLSTATE[HY000] [1045] Access denied
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
php artisan config:clear
SQLSTATE[42S02] Table not found
php artisan migrate
php artisan migrate:status
php artisan migrate:fresh --seed
QueryException with foreign key constraint
Schema::disableForeignKeyConstraints();
Schema::enableForeignKeyConstraints();
Route Errors
404 Not Found - Route does not exist
php artisan route:list
php artisan route:list --name=users
php artisan route:clear
MethodNotAllowedHttpException
Route::post('/submit', [FormController::class, 'store']);
Route::put('/update/{id}', [FormController::class, 'update']);
<form method="POST" action="/update/1">
@csrf
@method('PUT')
</form>
View Errors
View [name] not found
php artisan view:clear
Undefined variable in view
return view('users.index', [
'users' => $users,
'total' => $total,
]);
return view('users.index', compact('users', 'total'));
Middleware Issues
TokenMismatchException (CSRF)
<form method="POST" action="/submit">
@csrf
<!-- form fields -->
</form>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
protected $except = [
'stripe/*',
'webhook/*',
];
Unauthenticated / 403 Forbidden
php artisan route:list --columns=uri,middleware
Queue and Job Failures
Job failed without reason
php artisan queue:failed
php artisan queue:retry <job-id>
php artisan queue:retry all
php artisan queue:flush
Jobs not processing
php artisan queue:work
QUEUE_CONNECTION=redis
php artisan queue:restart
Cache and Session Problems
Session not persisting
php artisan session:clear
SESSION_DRIVER=file
chmod -R 775 storage/
chown -R www-data:www-data storage/
Config/cache showing old values
php artisan optimize:clear
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:
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:
protected function gate()
{
Gate::define('viewTelescope', function ($user) {
return in_array($user->email, [
'admin@example.com',
]);
});
}
Laravel Debugbar
Quick inline debugging for web pages.
Installation:
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:
composer require spatie/laravel-ray --dev
Usage:
ray($variable);
ray($var1, $var2)->green();
ray()->measure();
ray()->pause();
ray()->showQueries();
Built-in Debugging Functions
dd($variable);
dd($user, $posts, $comments);
dump($variable);
ddd($variable);
@dd($variable)
@dump($variable)
Log::debug('Message', ['context' => $data]);
Log::info('User logged in', ['user_id' => $user->id]);
Log::error('Payment failed', ['order' => $order]);
Artisan Tinker
Interactive REPL for testing code:
php artisan tinker
>>> User::where('active', true)->count()
=> 42
>>> $user = User::find(1)
>>> $user->posts()->count()
>>> app(UserService::class)->processUser($user)
The Four Phases of Laravel Debugging
Phase 1: Root Cause Investigation
Check Logs First:
tail -f storage/logs/laravel.log
grep -i "error\|exception" storage/logs/laravel.log | tail -50
cat storage/logs/laravel-2025-01-11.log
Verify Configuration:
php artisan env
php artisan config:show
php artisan config:show database
php artisan config:show queue
php artisan config:clear && php artisan config:cache
Check Application State:
php artisan up
php artisan schedule:list
php artisan route:list
php artisan event:list
Phase 2: Pattern Analysis
Compare with Laravel Conventions:
| Component | Convention | Common Mistake |
|---|
| Models | App\Models\User (singular) | Using plural names |
| Controllers | UserController | Missing Controller suffix |
| Migrations | create_users_table (plural) | Singular table names |
| Views | resources/views/users/index.blade.php | Wrong directory structure |
| Routes | RESTful naming | Non-standard HTTP methods |
Check for Common Anti-patterns:
$users = User::all();
foreach ($users as $user) {
echo $user->profile->bio;
}
$users = User::with('profile')->get();
foreach ($users as $user) {
echo $user->profile->bio;
}
Verify Dependencies:
composer show
composer diagnose
composer dump-autoload
Phase 3: Hypothesis and Testing
Create Focused Tests:
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class UserTest extends TestCase
{
use RefreshDatabase;
public function test_user_can_be_created()
{
$response = $this->post('/users', [
'name' => 'Test User',
'email' => 'test@example.com',
]);
$response->assertStatus(201);
$this->assertDatabaseHas('users', [
'email' => 'test@example.com',
]);
}
}
Run Tests:
php artisan test
php artisan test tests/Feature/UserTest.php
php artisan test --filter=test_user_can_be_created
php artisan test --coverage
./vendor/bin/pest
Test in Isolation:
php artisan tinker
>>> User::factory()->create()
>>> $user->notify(new WelcomeNotification)
QUEUE_CONNECTION=sync php artisan your:command
php artisan migrate:fresh --seed && php artisan test
Phase 4: Implementation and Verification
Apply Fix:
php artisan optimize:clear
composer dump-autoload
php artisan queue:restart
php artisan config:cache
php artisan route:cache
php artisan view:cache
Verify Fix:
php artisan test
tail -f storage/logs/laravel.log
php artisan queue:work --verbose
php artisan about
Quick Reference Commands
Clearing and Caching
php artisan optimize:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan cache:clear
php artisan event:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
Database Commands
php artisan migrate:status
php artisan migrate
php artisan migrate:rollback
php artisan migrate:fresh --seed
php artisan db:show
php artisan db
Queue Commands
php artisan queue:failed
php artisan queue:retry <id>
php artisan queue:retry all
php artisan queue:flush
php artisan queue:work --verbose
php artisan queue:restart
Route Commands
php artisan route:list
php artisan route:list --name=api
php artisan route:list --path=users
php artisan route:list --columns=method,uri,name,action
Debugging Commands
php artisan about
php artisan tinker
php artisan env
php artisan config:show
php artisan schedule:list
Environment-Specific Debugging
Development
APP_DEBUG=true
APP_ENV=local
LOG_CHANNEL=stack
LOG_LEVEL=debug
Enable all debugging tools:
- Laravel Telescope
- Laravel Debugbar
- Ray
Production
APP_DEBUG=false
APP_ENV=production
LOG_CHANNEL=stack
LOG_LEVEL=error
Use:
- Error tracking services (Sentry, Bugsnag)
- Log aggregation (Papertrail, Loggly)
- APM tools (New Relic, Scout)
Never expose detailed errors in production.
Logging Best Practices
Structured Logging
Log::info('Order processed', [
'order_id' => $order->id,
'user_id' => $order->user_id,
'total' => $order->total,
'items_count' => $order->items->count(),
]);
Log::debug('Detailed debugging info');
Log::info('Normal operational events');
Log::warning('Unusual but not errors');
Log::error('Runtime errors');
Log::critical('System is unusable');
Custom Log Channels
'channels' => [
'payments' => [
'driver' => 'daily',
'path' => storage_path('logs/payments.log'),
'level' => 'info',
'days' => 30,
],
],
Log::channel('payments')->info('Payment processed', ['id' => $payment->id]);
Additional Resources