Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Error Solutions Laravel Package

spatie/laravel-error-solutions

Shows helpful, actionable “solutions” directly on Laravel’s error page, explaining likely causes and fixes. Some solutions are runnable with one click (e.g., generate APP_KEY), speeding up debugging during local development.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-error-solutions
    

    Publish the config file:

    php artisan vendor:publish --provider="Spatie\ErrorSolutions\ErrorSolutionsServiceProvider"
    
  2. First Use Case:

    • Trigger an error in your Laravel app (e.g., 1/0 in a route).
    • The error page will now display predefined solutions (e.g., "Check your database connection" for PDOException).
    • No additional code needed—solutions are auto-loaded from the solutions.php config file.
  3. Where to Look First:

    • Config File: config/error-solutions.php (define custom solutions).
    • Error Solutions Class: app/Providers/ErrorSolutionsServiceProvider.php (extend default behavior).
    • Blade Template: resources/views/vendor/error-solutions/errors/solutions.blade.php (customize UI).

Implementation Patterns

Core Workflows

  1. Defining Solutions:

    • Add solutions to the solutions.php config:
      'solutions' => [
          'Symfony\Component\Debug\Exception\FatalErrorException' => [
              'title' => 'Fatal Error in Production',
              'solutions' => [
                  'Check your PHP error logs for the root cause.',
                  'Ensure your `APP_DEBUG` is `false` in `.env`.',
              ],
          ],
      ],
      
    • Dynamic Solutions: Use closures for runtime logic:
      'solutions' => [
          'Illuminate\Database\QueryException' => function () {
              return [
                  'title' => 'Database Query Failed',
                  'solutions' => [
                      "Verify your connection in `.env`: DB_".config('database.connections')."_URL",
                      "Check table `".request()->input('table', 'unknown')."` exists.",
                  ],
              ];
          },
      ],
      
  2. Integration with Custom Errors:

    • Extend the ErrorSolutions facade to handle custom exceptions:
      use Spatie\ErrorSolutions\Facades\ErrorSolutions;
      
      // In an Exception Handler:
      public function render($request, Throwable $exception) {
          if ($exception instanceof CustomException) {
              return ErrorSolutions::render($request, $exception, [
                  'title' => 'Custom Error',
                  'solutions' => ['Solution 1', 'Solution 2'],
              ]);
          }
      }
      
  3. Conditional Solutions:

    • Use when() in config to show solutions based on environment or context:
      'solutions' => [
          'RuntimeException' => [
              'solutions' => [
                  'Check your logs.' => ['env' => 'local'],
                  'Contact support.' => ['env' => 'production'],
              ],
          ],
      ],
      
  4. Localization:

    • Translate solutions via Laravel’s localization system:
      'solutions' => [
          'Symfony\Component\HttpKernel\Exception\NotFoundHttpException' => [
              'title' => __('error-solutions::not-found.title'),
              'solutions' => [
                  __('error-solutions::not-found.solution-1'),
              ],
          ],
      ],
      
    • Publish translations:
      php artisan vendor:publish --tag=laravel-error-solutions-lang
      

Advanced Patterns

  1. API Error Responses:

    • Use the ErrorSolutions::toArray() method to include solutions in API error responses:
      return response()->json([
          'error' => 'Validation failed',
          'solutions' => ErrorSolutions::toArray($exception),
      ], 422);
      
  2. Logging Solutions:

    • Log solutions alongside errors in App\Exceptions\Handler:
      public function report(Throwable $exception) {
          \Log::error($exception->getMessage(), [
              'solutions' => ErrorSolutions::toArray($exception),
          ]);
      }
      
  3. Dynamic Solution Generation:

    • Create a service to generate solutions based on exception data:
      class DynamicSolutionGenerator {
          public function generate(Throwable $exception): array {
              return [
                  'title' => 'Dynamic Solution',
                  'solutions' => [
                      "Check the variable `\$exception->getTrace()[0]['args'][0]`",
                  ],
              ];
          }
      }
      
    • Register it in ErrorSolutionsServiceProvider:
      $this->app->singleton(DynamicSolutionGenerator::class);
      
  4. Testing:

    • Mock solutions in tests:
      $exception = new \RuntimeException();
      $solutions = ErrorSolutions::getSolutions($exception);
      $this->assertContains('Test solution', $solutions);
      

Gotchas and Tips

Pitfalls

  1. Config Overrides:

    • Solutions in solutions.php override default ones. Use + to merge:
      'solutions' => [
          '+' => [
              'Symfony\Component\Debug\Exception\FatalErrorException' => [
                  'solutions' => ['Add this to existing solutions.'],
              ],
          ],
      ],
      
  2. Performance:

    • Avoid complex closures in solutions—they run on every error. Cache results if needed:
      'solutions' => [
          'RuntimeException' => function () {
              return Cache::remember('solutions.runtime', 60, function () {
                  return ['Cached solution'];
              });
          },
      ],
      
  3. Exception Matching:

    • Solutions are matched by exact exception class. Use getPrevious() for wrapped exceptions:
      'solutions' => [
          'Illuminate\Database\QueryException' => [
              'solutions' => [
                  'Check the underlying exception: '.($exception->getPrevious()?->getMessage() ?? 'None'),
              ],
          ],
      ],
      
  4. Blade Template Caching:

    • Clear Blade cache if UI changes aren’t reflecting:
      php artisan view:clear
      
  5. Environment-Specific Solutions:

    • Solutions in solutions.php are merged across environments. Use env() checks in closures:
      'solutions' => [
          'RuntimeException' => function () {
              return ['env' => app()->environment('local') ? 'Debug locally' : 'Deploy fix'];
          },
      ],
      

Debugging Tips

  1. Inspect Solutions:

    • Dump solutions for a given exception:
      use Spatie\ErrorSolutions\Facades\ErrorSolutions;
      dd(ErrorSolutions::getSolutions(new \RuntimeException()));
      
  2. Disable Solutions:

    • Temporarily disable solutions in config/error-solutions.php:
      'enabled' => env('APP_DEBUG') === false,
      
  3. Log Unhandled Exceptions:

    • Add a middleware to log solutions for uncaught errors:
      public function handle($request, Closure $next) {
          try {
              return $next($request);
          } catch (Throwable $e) {
              \Log::error('Unhandled error', [
                  'solutions' => ErrorSolutions::toArray($e),
              ]);
              throw $e;
          }
      }
      
  4. Custom Error Pages:

    • Override the default error view by publishing and modifying:
      php artisan vendor:publish --tag=laravel-error-solutions-views
      
    • Edit resources/views/vendor/error-solutions/errors/500.blade.php.

Extension Points

  1. Custom Solution Providers:

    • Register additional solution providers in ErrorSolutionsServiceProvider:
      $this->app->make(\Spatie\ErrorSolutions\ErrorSolutions::class)
          ->addSolutionProvider(new class {
              public function getSolutions(): array {
                  return [
                      'App\Exceptions\CustomException' => [
                          'title' => 'Custom Error',
                          'solutions' => ['Custom solution.'],
                      ],
                  ];
              }
          });
      
  2. Solution Events:

    • Listen for solution generation events (via error-solutions::solutions-generated):
      Event::listen('error-solutions::solutions-generated', function ($solutions, $exception) {
          // Log or modify solutions dynamically
      });
      
  3. Solution API:

    • Extend the ErrorSolutions class to add methods:
      namespace Spatie\ErrorSolutions;
      
      class ErrorSolutions extends \Spatie\ErrorSolutions\ErrorSolutions {
          public function getSolutionCount(Throwable $exception): int {
              return count($this->getSolutions($exception));
          }
      }
      
  4. Database-Backed Solutions:

    • Store solutions in a database table and fetch them dynamically:
      'solutions' => [
          'RuntimeException' => function () {
              return Solution::where('exception', 'RuntimeException')->first()->solutions;
          },
      ],
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport