Share This
//How Developers “Play” with Laravel Tinker

How Developers “Play” with Laravel Tinker

What is Tinker?

Laravel Tinker is a powerful REPL for the Laravel framework, powered by the PsySH package.
— Laravel Doc

Laravel Tinker is a tool for interacting with the database without the need to create routes. It is used with “PHP artisan” to create objects or modify data. “PHP artisan” is a command-line interface available in Laravel. Tinker is a command-line tool that works with “PHP artisan”. A Tinker allows you to create objects, insert data into the database, etc.

When to Use Tinker?

When a developer wants to see the results of queries, the fastest way is to do some processing like creating Controllers, routes, Models, etc. However, with php artisan tinker, we can quickly see the output. Tinker allows us to directly interact with the data via our application, using commands like stop() or dd() and even print_r().

How Does Tinker Work?

To get started with Tinker, just open the terminal and run the command php artisan tinker. This will open an interactive command-line environment for you. Here, you can type and run PHP commands to interact with your Laravel application. Try typing the command User::all() to get all the users in your database. You’ll get a list of user objects in your application. It’s simple and fast, right?

php artisan tinker

1. Query database

  • Query with conditions (multiple conditions):

\App\Models\Post::query() \

->with(‘user’) \

->where(‘count_view’, ‘>’, 200) \

->whereRaw(‘month(created_at) = ?’, [Carbon\Carbon::now()->month]) \

->orderByDesc(‘count_view’) \

->limit(10) \

->get();

  • Add a new record:

$user = new App\Models\User;

$user->email = “[email protected]

$user->name = “RCVN”

$user->password = \Hash::make(‘gX6JgDbmNd)97FS*’)

$user->save();

  • Delete a record from the database:

$user = App\Models\User::where(‘name’, ‘like’, ‘%leone%’)->first();

$user->delete();

2. Write function in Tinker

A function usually consists of multiple lines, but if you press enter, Tinker will interpret that as the end of the command. Therefore, to write a function in Tinker, you can use \ to terminate each line and continue the next line.

function sayHelloName($userId) { \

$user = App\Models\User::find($userId); \

return “Hello {$user->name}”; \

}

> sayHelloName(101)

= “Hello RCVN”

3. Up site/down site in a flash (maintenance mode)

Bring the website down with ease.

After debugging, bring the website back up.

4. View the source code of a function or class

show <functionName>

5. Tinker Commands

Similar to the Artisan command-line application, Tinker provides many commands and utilities that simplify the debugging process and executing code from the command line. The table below lists all the commands Tinker provides (these commands can be explored in Tinker REPL using the help command):

CommandDescriptionAlias
helpDisplay a list of Tinker commands.?
docRead documentation for an object, class, constant, method, or property.rtfm, man
lsList local variables, methods, constants, traits, or class.list, dir
showShow the source code for an object, class, constant, method, or property.
wtfShow the backtrace of the most recent exception.last-exception, wtf?
whereamiShow where you are in the code.
traceShow the current call stack.
throw-upThrow an exception out of the Psy Shell.
bufferDisplay (or clear) the input buffer contents.buf
clearClear the Psy Shell screen.
historyDisplay Psy Shell history.hist
exitEnd the current session and return to the caller.quit, q
clear-compiledClear compiled class files.
downPut the application in maintenance mode.
envDisplay the current environment configuration.
optimizeOptimize the framework for better performance.
upBring the application out of maintenance mode.
migrateRun database migrations.
schedule:list List the scheduled tasks.
schedule:runRun the scheduled tasks.

Use Laravel Tinker directly in the browser

If you’ve been using Tinker in the terminal, you’ve probably felt the frustration of having to copy/paste long code (like writing functions in Tinker). Well, laravel-web-tinker is exactly what you need to remove that frustration.

Like any other package, you can install it with just a few commands:

composer require spatie/laravel-web-tinker –dev

php artisan web-tinker:install

php artisan vendor:publish –provider=”Spatie\WebTinker\WebTinkerServiceProvider” –tag=”config”

Change the config in the file:

And now you can access localhost:8000/tinker and experience it:

Conclusion

In this article, we introduced the basics of using Tinker on both the terminal and web interface. We hope the article has provided useful information for readers and helps you on your journey to mastering Laravel.

References: Laravel Doc

Laravel web Tinker

Hồ Nguyễn Văn Nhật
PHP Developer

APPLY NOW






    Benefits

    SALARY & BONUS POLICY

    RiverCrane Vietnam sympathizes staffs' innermost feelings and desires and set up termly salary review policy. Performance evaluation is conducted in June and December and salary change is conducted in January and July every year. Besides, outstanding staffs receive bonus for their achievements periodically (monthly, yearly).

    TRAINING IN JAPAN

    In order to broaden staffs' view about technologies over the world, RiverCrane Vietnam set up policy to send staffs to Japan for study. Moreover, the engineers can develop their career paths in technical or management fields.

    ANNUAL COMPANY TRIP

    Not only bringing chances to the staffs for their challenging, Rivercrane Vietnam also excites them with interesting annual trips. Exciting Gala Dinner with team building games will make the members of Rivercrane connected closer.

    COMPANY'S EVENTS

    Activities such as Team Building, Company Building, Family Building, Summer Holiday, Mid-Autum Festival, etc. will be the moments worthy of remembrance for each individual in the project or the pride when one introduces the company to his or her family, and shares the message "We are One".

    INSURANCE

    Rivercrane Vietnam ensures social insurance, medical insurance and unemployment insurance for staffs. The company commits to support staffs for any procedures regarding these insurances. In addition, other insurance policies are taken into consideration and under review.

    OTHER BENEFITS

    Support budget for activities related to education, entertainment and sports. Support fee for purchasing technical books. Support fee for getting engineering or language certificates. Support fee for joining courses regarding technical management. Other supports following company's policy, etc.

    © 2012 RiverCrane Vietnam. All rights reserved.

    Close