Introduction to Laravel Tinker
In native PHP, you can use the php -a
command Use interactive Shell:
# php -a php > $msg = "Hello world!"; php > print $msg; Hello world! php > $num = array_sum([1, 2, 3]); php > print $num; 6
In addition, you can also use PsySH . Compared with the native php -a
, PsySH has more advanced features and is more powerful.
Install globally through Composer:
composer g require psy/psysh:@stable
Then execute psysh
on the command line to enter the interactive shell (you need to ensure that the bin
of global Composer is directory in the system path), you can write various codes in PsySH, print statements, calculate expressions, write functions, etc.
Laravel Tinker is implemented based on PsySH. Through Tinker, we can realize various interactions with Laravel applications on the command line, including additions, deletions, modifications and queries of the database.
You can enter the interactive shell of Laravel Tinker through php artisan tinker
on the command line.
View help documentation
In Laravel Tinker, the doc
command can be used to view the help documentation for a certain function or method, for example, view the helper functionconfig( )
How to use:
doc config show config
Run Artisan command
Runphp artisan tinker
is equivalent to starting the Laravel application from the console, before running the interactive command , the tinker
command will add some commands to the Shell, these commands are defined in the $commandWhitelist
attribute of Laravel\Tinker\Console\TinkerCommand
:
protected $commandWhitelist = [ 'clear-compiled', 'down', 'env', 'inspire', 'migrate', 'optimize', 'up', ];
So, these commands can be run directly in the Tinker Shell:
>>> inspire >>> env
Testing Laravel Code
You can use the console to create a new model, save it to the database, and then query this Records.
php artisan tinker >>> migrate >>> use App\User; >>> $user = new User(); >>> $user->name = "test"; >>> $user->email = "test@163.com"; >>> $user->password = bcrypt('123456'); >>> $user->save(); >>> $user = User::where('email', 'test@163.com')->first(); >>> factory(User::class, 3)->create(); >>> >>> $user = App\User::find(1); >>> $user->delete(); >>> >>> $log = app('log'); >>> $log->info('test');