This post is dedicated to an underappreciated component of Laravel – the tinker command that you can run with php artisan tinker
. The command is built into every Laravel application and you can use it to run code within the context of your application. Let's explore what this means.
Tinker is a REPL (read-eval-print loop) on top of PsySH. It takes your command line input, evaluates it and prints the output to the console. So instead of using your database management tool and writing an SQL query to get the amount of users in your database, you can simply run App\User::count()
and get => 10
as the result.
Tinker with autocompletion, a multi-line code editor, code snippets and magic comments.
Learn moreThe php artisan tinker
command bootstraps your application and waits for new commands when this finishes. It keeps the application state until you close leave the tinker command with exit
, Ctrl+C
or close the terminal. This means that you have to initialize a new tinker session every time you change your code to get the latest version – but it allows you to define new variables that are accessible until you end the tinker session.
All the time! We use tinker in development and on production for many scenarios. The most common use case is accessing the database via Laravel Eloquent Models.
Tinker is very convenient if you want to create test data in development – simply create two new test users with their factory.
User::factory()->count(2)->create()
This command uses the model factory for users and creates two new users. Your output of this command should look similar to this – with different usernames and emails.
=> Illuminate\Database\Eloquent\Collection {#4612 all: [ App\Models\User {#4616 gender: "male", firstname: "Orie", lastname: "Rath", }, App\Models\User {#4620 gender: "female", firstname: "Karlie", lastname: "Ruecker", }, ], }
Let's change the last name of the second user with php artisan tinker (type and confirm every line separately)
$user->lastname = 'Smith';$user->save();
If this works, tinker returns => true
If you don't want to run multiple commands and the model supports mass assignments, you can run this in a single line.
There are no limits what you can do with tinker as long as you are able to squeeze your code into one line or can execute the code line by line. If you want to push this to the next level, you can use Tinkerwell to write multiple lines of code and run them at once. This is very handy if you work with Laravel Collections or use loops – or simply like well-formatted code.
With tinker, you have access to all PHP functions and helpers that Laravel provides.
Instead of googling for an internet service that lets your generate UUIDs, you can use tinker and generate one with the Laravel Str helper.
Str::uuid()
This instantly generates an UUID for you.
=> Ramsey\Uuid\Lazy\LazyUuidFromString {#4632 uuid: "a1d56de1-455d-4275-8812-c3e28d45428e", }
Str::slug('The ultimate guide to php artisan tinker')
=> "the-ultimate-guide-to-php-artisan-tinker"
now()->addMonths(3)->startOfWeek()
=> Illuminate\Support\Carbon @1627862400 {#5507 date: 2021-08-02 00:00:00.0 UTC (+00:00), }
base64_encode('The ultimate guide to php artisan tinker')base64_decode('VGhlIHVsdGltYXRlIGd1aWRlIHRvIHBocCBhcnRpc2FuIHRpbmtlcg==')
=> "VGhlIHVsdGltYXRlIGd1aWRlIHRvIHBocCBhcnRpc2FuIHRpbmtlcg=="=> "The ultimate guide to php artisan tinker"
Ok, you get it.
You can dispatch jobs with tinker and add data to this job too. This is a real time-saver when you develop a new job and there are multiple steps involved to trigger the job. Imagine that you have a job that fulfills an order in an ecommerce system. You can either place many orders to test the job or simply dispatch it via tinker. Remember to restart your tinker session if you change the code of the job – or dispatch the job with Tinkerwell where every command runs on the latest code base.
$order = new Order(['invoice_id' => 12345, 'item' => 'Tinker Fangirl Mug']);dispatch(new OrderPlacedJob($order));
Similar to Jobs, you can also send Laravel Notifications & Mailables via tinker. You are in the context of your application and can send them with a simple call.
(new User)->notify(new InvoicePaid($invoice);
The composer.json
file of your application contains the major and minor version of your Laravel application. If you want to know which Laravel version you use exactly, you can get this via app()->version()
.
app()->version()
=> "8.24.0"
Tinker is a powerful tool for all Laravel developers but you can push this to a next level. Tinkerwell is a code editor for macOS, Windows and Linux that is entirely dedicated to tinker. It comes with multiline support, SSH connections and allows you to tinker with multiple applications at the same time.
With Tinkerwell, there is no need to reload a tinker session, as Tinkerwell evaluates the current state of your code and does not keep the application state.
The multiline support makes it easy to use Laravel Collections or foreach loops in tinker. To continue with an example, you can update multiple users at the same time by using collections on the Eloquent result.
App\User::whereNull('confirmed_at') ->get() ->each(function ($user) { $user->update([ 'confirmed_at' => $user->created_at->addDay(), ]); });
When working with APIs, the Http
facade of Laravel provides a fluent interface to send GET
and POST
requests to an API. You can use this to access the API and see how the data of this API looks or send data to the API before you implement the API directly in your application.
$apiKey = 'Your-Forge-API-Key'; $response = Http::withHeaders([ 'accept' => 'application/json' ]) ->withToken($apiKey) ->get('https://forge.laravel.com/api/v1/servers') ->json(); collect($response['servers'])->pluck('name');
=> Illuminate\Support\Collection {#1046 all: [ "HELO-cloud", "bc-dev", "bc-prod-01", "bc-prod-02", "bc-prod-03", "bc-website", "expose", "expose-eu-1", ... ], }
Tinkerwell is a mighty desktop application for every Laravel developer and more than 10,000 developers are already using Tinkerwell, including the Laravel team itself.
“Seriously, Tinkerwell is great, I genuinely use it every single day for testing snippets or checking production data.”James Brooks
Developer at Laravel
“Tinkerwell's intuitive and user-friendly interface. It offers a clean and easy-to-navigate design, making it accessible to both experienced and novice Laravel developers.”Somaiya Utsav
Laravel Developer at Freshbits web solution
The must-have companion to your favorite IDE. Quickly iterate on PHP code within the context of your web application.
Buy now Learn more