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 (powered by PsySH) for Laravel applications. Quickly run PHP and Artisan code, inspect models and services, and debug in a live console with your app’s full context loaded.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Laravel Tinker is included by default in Laravel 5.5+. No additional installation is required.
  2. First Use: Launch Tinker via Artisan:
    php artisan tinker
    
  3. Basic Interaction: Start experimenting immediately. For example:
    >>> $user = App\Models\User::first();
    >>> $user->name
    

Where to Look First

  • Laravel Documentation: Laravel Tinker Docs for official usage and examples.
  • PsySH Documentation: Understand the underlying REPL capabilities (e.g., tab completion, history, and syntax highlighting).
  • Artisan Commands: Use php artisan tinker --help to explore available options like --execute for one-off commands.

First Use Case

Debugging a Model Query:

>>> $posts = App\Models\Post::where('published', true)->get();
>>> $posts->count()
10
>>> $posts->first()->title
"My First Post"

Implementation Patterns

Common Workflows

  1. Interactive Debugging:

    • Inspect Eloquent models, relationships, and query results dynamically.
    • Example: Traverse a complex relationship chain:
      >>> $user = App\Models\User::find(1);
      >>> $user->posts()->where('views', '>', 1000)->get()
      
  2. Testing Logic Snippets:

    • Quickly validate business logic without writing tests or routes.
    • Example: Test a custom validation rule:
      >>> $validator = Validator::make(['email' => 'test@example.com'], ['email' => 'required|email']);
      >>> $validator->passes()
      true
      
  3. One-Off Commands:

    • Use --execute to run a command and exit:
      php artisan tinker --execute="App\Models\User::all()->count()"
      
  4. Service Container Inspection:

    • Explore bound services and providers:
      >>> app()->bound('cache')
      true
      >>> app('cache')->store()
      "file"
      
  5. Custom Casters:

    • Extend output formatting for custom classes (e.g., HtmlString or Stringable).
    • Example: Register a caster for a custom Money class:
      >>> Psy\Output\OutputInterface::getCasters()->add('App\Money', function ($money) {
      ...     return '$' . $money->getAmount();
      ... });
      

Integration Tips

  • Autoloading: Tinker automatically loads your project’s autoloader, so all classes are available.
  • Environment Context: Runs in the same environment as your Laravel app (e.g., .env variables, configured services).
  • Tab Completion: Use Tab to autocomplete classes, methods, and properties (e.g., App\Models\UApp\Models\User).
  • History: Commands are saved to ~/.psysh_history (or project-specific if configured).
  • Exit: Type exit or press Ctrl+D to leave Tinker.

Gotchas and Tips

Pitfalls

  1. Database Transactions:

    • Tinker runs in the same process as your app, so database transactions may persist unexpectedly. Use DB::beginTransaction() and DB::rollBack() carefully.
    • Example:
      >>> DB::beginTransaction();
      >>> App\Models\User::create(['name' => 'Test']);
      >>> DB::rollBack(); // Undo the creation
      
  2. Memory Usage:

    • Loading large datasets (e.g., User::all()) can consume significant memory. Use cursor() for lazy loading:
      >>> $users = App\Models\User::cursor();
      >>> foreach ($users as $user) { ... }
      
  3. PsySH Prompts:

    • Avoid trust project prompts by ensuring your composer.json has correct autoloading or use --no-interaction:
      php artisan tinker --no-interaction
      
  4. Exit Code Issues:

    • Exceptions in Tinker may not always return the correct exit code. Use --execute for scripts where exit codes matter.
  5. Whitelisted Commands:

    • Some Artisan commands (e.g., migrate:fresh) are restricted for security. Check the whitelist or use --execute to bypass.

Debugging Tips

  • Inspect Variables: Use var_dump(), print_r(), or dd() (dumps and dies) for deep inspection.
    >>> dd($user->toArray());
    
  • Enable Debug Mode: Ensure APP_DEBUG=true in .env for full error traces.
  • Clear Cache: If classes aren’t autoloading, clear the cache:
    php artisan optimize:clear
    
  • PsySH Debugging: Use Psy\Shell::getInstance()->debug() to inspect PsySH internals.

Extension Points

  1. Custom Casters:

    • Register casters for better output formatting. Example for a Carbon instance:
      Psy\Output\OutputInterface::getCasters()->add('Carbon\Carbon', function ($carbon) {
          return $carbon->format('Y-m-d H:i:s');
      });
      
  2. Aliases:

    • Create shortcuts for frequent commands in your ~/.psyshrc.php or project’s bootstrap/app.php:
      Psy\Configuration::getInstance()->addAliases([
          'u' => 'App\Models\User',
          'p' => 'App\Models\Post',
      ]);
      
  3. Environment Setup:

    • Pre-load data or configure Tinker in bootstrap/app.php:
      $app->booting(function () {
          if ($this->runningInConsole() && php_sapi_name() === 'cli') {
              $app->make('Psy\Configuration')->setOption('historyFile', storage_path('tinker_history'));
          }
      });
      
  4. Integration with Tests:

    • Use Tinker in phpunit.xml for interactive debugging during tests:
      <env name="APP_DEBUG" value="true"/>
      

Pro Tips

  • Chain Commands: Use ; to chain commands (e.g., User::first(); $user->posts;).
  • Multiline Input: Press Shift+Enter for multiline code blocks.
  • Syntax Highlighting: Works with most modern terminals (e.g., iTerm2, VS Code’s integrated terminal).
  • Remote Debugging: Combine with Laravel Forge/Laravel Vapor for remote REPL access via SSH.
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony