What's the difference between Tinker and seeder in laravel?
Tinker and seeder are powerful tools that can help you manage and maintain your database with ease, you can use them for testing.
Tinker uses a command line or terminal to write the same code that u do in your editor to manage your data but there is one different thing. when you use Tinker, the code will be applied to your database but it won't be in your source code, it will be only in the terminal and execute one time if you don't repeat it. but when you write your code directly in the file, it will be always there. You can say that tinker is like a virtual code that will be applied but it won't exist in your code.
Now How to use it?
1- open the terminal on your project
php artisan tinker
Now it will work and you can write all your code to manage data in the database.
For example:
User::create([
'name'=>'ali kanaan',
'email'=>'ali44@gmail.com',
'password'=>Hash::make('anything')
]);
// This code will insert the data in database
Now let's talk about Seeder.
In seeder, you write the code in your file, and when you want to manage your database you can do it by calling the seeder names in the terminal. Seeder has an advantage when you use it because you can do many queries at the same time and if you want to do it all again, There is no need to write all code again like a tinker, you can only call it in the terminal and it will be always in your files so if you have a team and you want to only enter a specific data to a database or manage it, the code exists and only they need to call or run it.
For example:
php artisan make:seeder UserSeeder
/*
UserSeeder is a name only and u can give any name u want to the seeder
but don't forget to follow the convention name
*/
Now your seeder will be created in the database folder :
database/seeders/UserSeeder
now open the seeder file and write in the function any code to manage data,
For example:
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
// Inserting in database
User::create([
'name'=>'moemen saadeh',
'email'=>'moemen3@gmail.com',
'password'=>Hash::make('12345678')
]);
}
}
// Now open your terminal to run the code
php artisan make:seeder UserSeeder
// Now check the data in database it will be inserted