PHP Classes

How to Use Laravel Tinker Commands to Become a More Productive PHP Developer

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Use Laravel Ti...   Post a comment Post a comment   See comments See comments (0)   Trackbacks (0)  

Author:

Viewers: 569

Last month viewers: 6

Categories: PHP Tutorials, Sponsored, Republished

Laravel is a popular framework that grows with the collaboration of many PHP developers who create excellent components and tools. The work of the Laravel community helps to increase the opportunities for all developers who use the resources provided by the Laravel developers’ community.

Laravel Tinker is one of the components that improves the lives of many PHP developers who use Laravel. The fact is that Laravel Tinker allows developers to use an interactive shell to run PHP commands inside their applications. Laravel Tinker enables developers to inspect values to find and fix issues faster that the application may have.

Read this article to learn more about Laravel Tinker and how you can use it to improve your daily work productivity when you are developing applications based on Laravel.




Loaded Article

In this article you will learn:

What Is Laravel Tinker

How to Use Laravel Tinker

Laravel Tinker Examples in Practice

Using Laravel Tinker with Eloquent Models

How to Use a Laravel UUID Generator with Laravel Str Helper

How to Use a Laravel Slug Generator from a Headline Parameter

How to Use Laravel to Get the Current Date and Time and Return the First Day of the Week in 3 Months

How to Use Laravel to Get Base64 Encode and Decode of a String

How Can You Use Laravel Tinker to Dispatch Jobs

How to Send Laravel Notifications using Tinker

How to Use the Laravel Version Check Command

How to Improve the Lives of Laravel Developers with Tinkerwell

Using Laravel Collections to Get an Array of Objects

Laravel API Testing Example

How Can You Get Tinkerwell so You Can Start Becoming More Productive Developing Laravel Applications


What Is Laravel 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 to Use Laravel Tinker

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 exitCtrl+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.

Laravel Tinker Examples in Practice

You may wonder when you should use Tinker in your Laravel projetcs. The answer is: 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.

Using Laravel Tinker with 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",
         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.

How to Use a Laravel UUID Generator with Laravel Str Helper

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",
   }

How to Use a Laravel Slug Generator from a Headline Parameter

Str::slug('The ultimate guide to php artisan tinker')
=> "the-ultimate-guide-to-php-artisan-tinker"

How to Use Laravel to Get the Current Date and Time and Return 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),
   }

How to Use Laravel to Get Base64 Encode and Decode of a String

base64_encode('The ultimate guide to php artisan tinker')
base64_decode('VGhlIHVsdGltYXRlIGd1aWRlIHRvIHBocCBhcnRpc2FuIHRpbmtlcg==')
=> "VGhlIHVsdGltYXRlIGd1aWRlIHRvIHBocCBhcnRpc2FuIHRpbmtlcg=="
=> "The ultimate guide to php artisan tinker"

Ok, you get it.

How Can You Use Laravel Tinker to 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));

How to Send Laravel Notifications using Tinker

Similar to Jobs, you can also send Laravel Notifications and 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);

How to Use the Laravel Version Check Command

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"

How to Improve the Lives of Laravel Developers with Tinkerwell

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 Laravel Collections to Get an Array of Objects

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(),
    ]);
  });

Laravel API Testing Example

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",
       ...
     ],
   }

How Can You Get Tinkerwell so You Can Start Becoming More Productive Developing Laravel Applications

Tinker is an excellent Laravel package by itself. Tinkerwell is a tool that makes your life as a Laravel developer help save you countless hours while trying to find and fix issues in your application code.

Tinkerwell is a mighty desktop application for every Laravel developer. More than 7,000 developers are already using Tinkerwell, including the Laravel team itself.

If you would like to get Tinkerwell, just go to its site and download it now. There are versions available to run under Windows, macOS X, and Linux.




You need to be a registered user or login to post a comment

Login Immediately with your account on:



Comments:

No comments were submitted yet.




  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Use Laravel Ti...   Post a comment Post a comment   See comments See comments (0)   Trackbacks (0)