How to use Tinker in Laravel Application

Tinker is a beautiful laravel package. Laravel Tinker is a powerful REPL for the Laravel framework. REPL stands for Read–Eval–Print Loop. This feature is powered by PsySH console.

The main function of tinker is to allow you to directly interact with laravel application from the command line such as Eloquent ORM, jobs, events, and more. In this article, we will do CRUD operations with tinker. It comes default with laravel. But, you may use it in other framework projects by installing it via composer. To install it, run the below command:

Database Setup

Before we get started playing with tinker, we need to setup a database for our application. Let’s create a new database called kodementor and do necessary configurations in .env file.

Migration

After database setup, we will migrate our default migration file for users table. To do so, run the artisan command:

Now, we can start playing with tinker to interact with our database. Please note that tinker is case sensitive. To enter in tinker environment, we need to run artisan command:

Seeding Database

Seeding database is one of the most frequently used technique using tinker. Using this method, we can populate our database in a single command using a factory. The following command will seed our database with 20 rows of data in our App\User model. Isn’t it nice?

seeding database with tinker

Accessing Database

After seeding, let’s access our users’ list. Simply write the code as you used to write in IDE.

You can also limit the number of records while accessing it from the database.

Also, you can retrieve only first record. Run the command:

Moreover, you can find any record using Id. Below code will return a user with id of 10.

Insert Record Manually

We used the factory to seed our database before, but we can do it manually as well. For this, we need to get the model and store it in a variable. Then, assign the attribute on the variable. After all necessary attributes have been set, we can finally call the save method.

Updating Database

You can also update any information from database. For this, get the record, assign new attribute and save to database.

Deleting Record

Obviously, we can also delete record using this package.

Reading Documentation

With the help of tinker, you can even read functions documentation. For this, we need to type doc before function name. Let’s try reading Laravel helper function in laravel.

You can also read PHP documentation but you need to download it in local. You can read on about PHP manual installation.

Conclusion

So, this is all about using tinker in laravel application. You can do a lot more besides the above-mentioned steps. For this, simply type help command so that you can see the capabilities built-in to tinker.