Introduction to Laravel Tinker: Using an Interactive Shell for Laravel Development
This article introduces Laravel Tinker, explains how to use PHP's interactive shell and PsySH, shows installation via Composer, demonstrates common Artisan commands, and provides code examples for interacting with Laravel models and the command whitelist within the Tinker environment.
Laravel Tinker is an interactive console built on top of PsySH that allows developers to execute PHP code within the context of a Laravel application, making it easy to experiment with models, database queries, and Artisan commands.
In native PHP you can start an interactive shell with php -a . For example:
<code># php -a
php > $msg = "Hello world!";
php > print $msg;
Hello world!
php > $num = array_sum([1, 2, 3]);
php > print $num;
6
</code>PsySH provides a richer feature set than the basic php -a shell. Install it globally via Composer:
<code>composer global require psy/psysh:@stable</code>After installation, run psysh to enter the enhanced interactive shell.
Laravel Tinker leverages PsySH. Start it with the Artisan command:
<code>php artisan tinker</code>Inside Tinker you can view documentation for functions or helpers using the doc command, e.g., doc config or show config to see how the config() helper works.
When you run php artisan tinker , a set of Artisan commands becomes available in the Tinker shell. These commands are defined in Laravel\Tinker\Console\TinkerCommand under the $commandWhitelist property:
<code>protected $commandWhitelist = [
'clear-compiled', 'down', 'env', 'inspire', 'migrate', 'optimize', 'up',
];
</code>Thus you can execute commands like inspire or env directly from the Tinker prompt.
Typical usage includes testing Laravel code. For example, you can create a new model, set its attributes, save it, query it, generate additional records with factories, delete it, and even write to the log:
<code>php artisan tinker
>> migrate
>> use App\User;
>> $user = new User();
>> $user->name = "test";
>> $user->email = "[email protected]";
>> $user->password = bcrypt('123456');
>> $user->save();
>> $user = User::where('email', '[email protected]')->first();
>> factory(User::class, 3)->create();
>> $user = App\User::find(1);
>> $user->delete();
>> $log = app('log');
>> $log->info('test');
</code>These examples demonstrate how Laravel Tinker streamlines development workflows by providing immediate feedback and a convenient environment for experimenting with application code.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.