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

Tinker Laravel Package

laravel/tinker

Laravel Tinker provides an interactive REPL for Laravel, letting you run PHP code and interact with your application from the command line via Artisan tinker. Great for debugging, testing ideas, and exploring models, services, and configuration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Tinker is included by default in Laravel. No additional installation is required.

  2. First Use: Launch Tinker via:

    php artisan tinker
    

    This opens an interactive REPL shell with access to your Laravel application’s container and helpers.

  3. First Use Case: Inspect a model or service immediately:

    // Example: Fetch and inspect a user
    $user = App\Models\User::find(1);
    $user->toArray();
    

Where to Look First

  • Laravel Documentation: Tinker in the Laravel Docs for core usage.
  • PsySH Features: Tinker is built on PsySH, so explore its documentation for advanced REPL tricks (e.g., history, custom commands).
  • Artisan Command: Run php artisan tinker --help for CLI options like --execute for one-liners.

Implementation Patterns

Core Workflows

  1. Interactive Debugging

    • Scenario: Debugging a failing job or service.
    • Pattern:
      // Simulate a job execution
      $job = new \App\Jobs\ProcessOrder($orderId);
      $job->handle(new \Illuminate\Bus\Dispatcher($app));
      
    • Tip: Use var_dump() or dd() (dump and die) for quick inspection.
  2. Model Exploration

    • Scenario: Querying and modifying Eloquent models dynamically.
    • Pattern:
      // Fetch and update a model
      $post = \App\Models\Post::first();
      $post->update(['title' => 'Updated Title']);
      $post->fresh()->title; // Verify changes
      
    • Tip: Chain methods like where() or with() directly in the REPL.
  3. Service Container Access

    • Scenario: Testing a bound service or middleware.
    • Pattern:
      // Resolve and test a service
      $mailer = app(\Illuminate\Mail\Mailer::class);
      $mailer->raw('Test email', function ($message) {
          $message->to('test@example.com');
      });
      
  4. One-Liners with --execute

    • Scenario: Running a quick command without entering the REPL.
    • Pattern:
      php artisan tinker --execute="App\Models\User::count()"
      
    • Use Case: CI/CD scripts, ad-hoc data checks, or automated testing.
  5. Custom Helpers

    • Scenario: Extending Tinker with project-specific shortcuts.
    • Pattern: Add a Tinker.php file in your project root with helper functions:
      // File: Tinker.php
      function u($id) {
          return \App\Models\User::findOrFail($id);
      }
      
    • Integration: Tinker auto-loads this file on startup.
  6. Testing Logic Snippets

    • Scenario: Prototyping a new feature or validating logic.
    • Pattern:
      // Test a validation rule
      $validator = \Validator::make(['email' => 'test@example.com'], [
          'email' => 'required|email'
      ]);
      $validator->passes(); // true/false
      

Integration Tips

  • Environment Awareness: Tinker respects your .env file, so database connections, queues, and configs are pre-loaded.
  • Artisan Commands: Access any Artisan command via Artisan::call():
    Artisan::call('migrate:status');
    
  • Event Dispatching: Test event listeners or queues:
    event(new \App\Events\OrderPlaced($orderId));
    
  • View Rendering: Render Blade templates dynamically:
    $html = view('emails.welcome', ['user' => $user])->render();
    

Gotchas and Tips

Pitfalls

  1. Database Transactions

    • Issue: Tinker runs in the same process as your app, so database changes persist unless wrapped in a transaction.
    • Fix: Use DB::transaction() to roll back changes:
      DB::transaction(function () {
          $user = new \App\Models\User();
          $user->save();
          // Changes rolled back if an exception occurs
      });
      
  2. Queue Jobs

    • Issue: Jobs dispatched in Tinker may not behave identically to production (e.g., no queue worker).
    • Fix: Use Bus::dispatchSync() for synchronous testing:
      Bus::dispatchSync(new \App\Jobs\ProcessOrder($orderId));
      
  3. PsySH Quirks

    • Issue: PsySH may prompt for project trust on first run (fixed in v2.11.1+).
    • Fix: Ignore or trust the project if prompted, or update Tinker:
      composer update laravel/tinker
      
  4. Model Events

    • Issue: Observers or model events may fire unexpectedly during inspection.
    • Fix: Temporarily disable observers or use static::withoutEvents():
      \App\Models\User::withoutEvents(function () {
          $user = \App\Models\User::find(1);
          $user->name = 'Test';
          $user->save(); // No observers triggered
      });
      
  5. Caching

    • Issue: Cached routes or config may not reflect recent changes.
    • Fix: Clear caches explicitly:
      Artisan::call('cache:clear');
      Artisan::call('config:clear');
      

Debugging Tips

  • Inspect Variables: Use dump() (from Laravel) or var_export() for detailed output.
  • Autocomplete: PsySH supports tab completion for classes, methods, and variables.
  • History: Use history to revisit past commands or !! to repeat the last command.
  • Custom Casters: Extend output formatting for complex objects (e.g., collections, APIs):
    Psy\Configuration::getInstance()->addCustomCaster(
        \App\Models\User::class,
        function ($user) {
            return "User#{$user->id}: {$user->name}";
        }
    );
    

Extension Points

  1. Custom REPL Configuration

    • Override PsySH settings in config/tinker.php (if it exists) or via Psy\Configuration:
      Psy\Configuration::getInstance()->setOption('colors', false);
      
  2. Pre-Loaded Code

    • Add a Tinker.php file to auto-load helpers, aliases, or setup code:
      // Tinker.php
      use App\Models\User as AppUser;
      alias('User', AppUser::class);
      
  3. Custom Commands

    • Register PsySH commands for project-specific tasks:
      Psy\Command\Command::add('list:users', function () {
          return \App\Models\User::all()->pluck('name');
      });
      
  4. Environment-Specific Setup

    • Use Tinker to load environment-specific data or mocks:
      if (app()->environment('local')) {
          \App\Models\User::factory()->create(['email' => 'local@example.com']);
      }
      

Performance Notes

  • Avoid Heavy Operations: Tinker is not optimized for production-like loads. Use transactions or rollbacks for destructive operations.
  • Memory Usage: Long-running sessions may consume memory. Exit with exit or Ctrl+D.
  • Queue Testing: For queue jobs, consider using Bus::fake() for assertions:
    Bus::fake();
    Bus::dispatch(new \App\Jobs\ProcessOrder($orderId));
    Bus::assertDispatched(\App\Jobs\ProcessOrder::class);
    
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