What is tinker?
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.
How does it work?
The 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.
When do you need it?
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.
Use Eloquent Models with tinker
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",
email: "jocelyn.schuster@example.org",
},
App\Models\User {#4620
gender: "female",
firstname: "Karlie",
lastname: "Ruecker",
email: "trycia.koelpin@example.org",
},
],
}
Let's change the last name of the second user with php artisan tinker (type and confirm every line separately)
$user = User::where('email', 'trycia.koelpin@example.org')->first();
$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.
User::where('email', 'trycia.koelpin@example.org')->first()->update(['lastname' => 'Carlson']);
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.
Generate UUIDs
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",
}
Create a slug from a headline
Str::slug('The ultimate guide to php artisan tinker')
=> "the-ultimate-guide-to-php-artisan-tinker"
Get the date of the first day of the week in 3 months
now()->addMonths(3)->startOfWeek()
=> Illuminate\Support\Carbon @1627862400 {#5507
date: 2021-08-02 00:00:00.0 UTC (+00:00),
}
Base64 encode and decode
base64_encode('The ultimate guide to php artisan tinker')
base64_decode('VGhlIHVsdGltYXRlIGd1aWRlIHRvIHBocCBhcnRpc2FuIHRpbmtlcg==')
=> "VGhlIHVsdGltYXRlIGd1aWRlIHRvIHBocCBhcnRpc2FuIHRpbmtlcg=="
=> "The ultimate guide to php artisan tinker"
Ok, you get it.
Dispatch jobs
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.
$order = new Order(['invoice_id' => 12345, 'item' => 'Tinker Fangirl Mug']);
dispatch(new OrderPlacedJob($order));
Send Notifications
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);
Check your current Laravel version
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"
Tinkerwell – php artisan tinker on steroids
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.
Using Collections
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(),
]);
});
Testing APIs
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 7,000 developers are already using Tinkerwell, including the Laravel team itself.
Top comments (0)