How To Use Laravel Tinker

Do you want to know how to use Laravel Tinker? Using Tinker we can interact with the database through command-line. In this article, we show you how to use Laravel Tinker.

Laravel is one of the most popular framework which is built in PHP. If you like a clean and neat code then Laravel should be your choice for building a web application. It comes with some built-in features like Artisan commands, Eloquent ORM, etc. Tinker is also one of them a built-in feature.

Tinker is a REPL(read-eval-print loop). REPL allows you to interact with your application through command-line. It’s commonly used for making simple database changes.

Why Need Of Laravel Tinker

Using Tinker, we can write actual PHP code through command-line. For instance, you need to add dummy data in your database table and you don’t have access to the database. In such case, you can insert data through Tinker. We can even update, delete table records in the database.

Having said that, let’s see how to use Laravel Tinker.

How To Use Laravel Tinker

When we install Laravel, we got this feature automatically. We don’t need to install Laravel Tinker separately.

To show you the use of Laravel Tinker, let’s assume we have table ‘products’ in the database. This table contains the columns name, description, etc.

Product Table

Now we will insert a row in the ‘products’ table using the Laravel Tinker.

Open the command prompt in your Laravel project. To use the tinker, we create a model which interacts with the table ‘products’.

php artisan make:model Product

PHP Artisan Make Model

Above command create a model ‘Product.php’ under the ‘app’ directory.

Next, run the below command.

php artisan tinker

PHP Artisan Tinker

We use the Eloquent ORM to insert a row in our database table. So write the below code in command-line.

$p = new App\Product;
$p->name = 'Test Product';
$p->description = 'Test Product Body';

PHP Artisan Tinker Insert Row

Above commands will insert a single row in the table ‘products’.

To delete the record we write the below code in a command-line.

$p = App\Product::find(1); //here '1' is the product id

PHP Artisan Tinker Delete Row

These are some basic examples of a Tinker. We hope you understand the flow of Laravel Tinker. Now, you can go ahead and explore it more.

Note: To come out of the Tinker from command-line type ‘Exit’ and press Enter.

If you liked this article, then please subscribe to our Youtube Channel for video tutorials.

2 thoughts on “How To Use Laravel Tinker

Leave a Reply

Your email address will not be published. Required fields are marked *