spatie/laravel-tinker-tools
Enables using short class names in Artisan Tinker sessions on older Laravel versions (built into Laravel 5.5+). Register ShortClassNames in .psysh.php and dump optimized autoload, then reference models like NewsItem::first() without full namespaces.
Installation (Laravel <5.5 only):
composer require spatie/laravel-tinker-tools
Publish the config (if needed):
php artisan vendor:publish --provider="Spatie\TinkerTools\TinkerToolsServiceProvider"
First Use Case: Launch Tinker:
php artisan tinker
Now use short class names directly:
User::first(); // Instead of \App\Models\User::first()
config/tinker-tools.php (if published) – Customize allowed namespaces.app/Providers/AppServiceProvider.php – Check for existing Tinker aliases.Short Class Resolution:
The package automatically resolves short class names (e.g., User) to fully qualified names (e.g., \App\Models\User) when:
app/ or database/ directories.Integration with Existing Code:
User::find(1) instead of \App\Models\User::find(1).MyService::newInstance().User::where(...)->get()->pluck('name').Custom Namespaces:
Extend the allowed namespaces in config/tinker-tools.php:
'namespaces' => [
'App\\',
'Database\\',
'Vendor\\Custom\\',
],
Aliasing Classes:
Override default behavior by defining aliases in AppServiceProvider:
use Spatie\TinkerTools\TinkerTools;
public function boot()
{
TinkerTools::addAlias('User', \App\Models\Admin::class);
}
Laravel 5.5+: The package is deprecated for Laravel 5.5+. Use Laravel’s built-in Tinker aliases instead:
use App\Models\User; // No package needed
Namespace Conflicts:
If two classes share the same short name (e.g., User in App and Vendor), the first matching namespace in config/tinker-tools.php wins.
Dynamic Classes:
Classes loaded dynamically (e.g., via class_alias()) may not resolve. Ensure they’re autoloaded.
Case Sensitivity:
Short names are case-sensitive. user::first() will fail unless the class is named exactly User.
Verify Resolution: Check if a class resolves by running:
\Spatie\TinkerTools\TinkerTools::resolveShortClassName('User');
Returns null if unresolved.
Clear Cache:
After modifying config/tinker-tools.php, run:
php artisan config:clear
Log Short Names:
Enable debug mode in config/tinker-tools.php:
'debug' => true,
Logs unresolved short names to storage/logs/laravel.log.
Custom Resolvers: Extend the resolver logic by binding a custom resolver to the container:
$this->app->bind(\Spatie\TinkerTools\ShortClassNameResolver::class, function () {
return new CustomShortClassNameResolver();
});
Tinker Commands:
Use the package’s TinkerTools facade in custom Tinker commands:
use Spatie\TinkerTools\TinkerTools;
TinkerTools::addAlias('DB', \Illuminate\Support\Facades\DB::class);
IDE Support:
Add @mixin in PHPStorm for short names:
// In a Tinker helper file (e.g., `app/Tinker.php`)
@mixin \App\Models\User
How can I help you explore Laravel packages today?