Tinker lets you talk to your database quickly using simple commands. It helps you test and try out database actions without making a full app.
0
0
Tinker for database interaction in Laravel
Introduction
You want to quickly add or change data in your database.
You need to check if your database records look right.
You want to test how your database queries work.
You want to try out Laravel model features without writing a full program.
You want to debug or fix data problems fast.
Syntax
Laravel
php artisan tinker
Run this command in your terminal inside your Laravel project folder.
Once inside Tinker, you can write PHP code to interact with your database models.
Examples
Starts the Tinker interactive shell.
Laravel
php artisan tinker
Fetches all records from the users table using the User model.
Laravel
User::all();
Creates and saves a new user record in the database.
Laravel
$user = new User(); $user->name = 'Anna'; $user->email = 'anna@example.com'; $user->save();
Finds the first user with the given email.
Laravel
User::where('email', 'anna@example.com')->first();
Sample Program
This example shows how to create a new user named Sam and save it to the database. Then it fetches all users and converts them to an array to see the data.
Laravel
<?php // Open terminal and run: // php artisan tinker // Inside Tinker shell, run these commands: $user = new User(); $user->name = 'Sam'; $user->email = 'sam@example.com'; $user->save(); $allUsers = User::all(); $allUsers->toArray();
OutputSuccess
Important Notes
Remember to have your database set up and connected in Laravel before using Tinker.
Tinker runs PHP code, so you can use any Laravel model or PHP logic inside it.
Use Ctrl+C to exit Tinker when done.
Summary
Tinker is a quick way to try database commands in Laravel.
You can create, read, update, and delete data easily inside Tinker.
It helps you learn and test without building full pages or scripts.