To insert a dummy user for testing purposes so you don't need to insert it manually each time you run `php artisan migrate:fresh`, you can use Laravel's seeding feature.
Here's a step-by-step guide to achieve this:
1. **Create a Seeder**: Generate a seeder class using Artisan that will insert the dummy user.
```bash
php artisan make:seeder UserSeeder
```
2. **Define Seeder Logic**: Update the `UserSeeder` class to insert the dummy user. Open `database/seeders/UserSeeder.php` and add the following code:
```php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
class UserSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
DB::table('users')->insert([
'user_id' => Str::uuid(),
'first_name' => 'John',
'middle_name' => 'D',
'last_name' => 'Doe',
'email' => 'john.doe@example.com',
'password' => Hash::make('password'), // Use a default password or any secure value
'role_id' => 1,
'created_at' => now(),
'updated_at' => now(),
]);
}
}
```
In this example:
- `Str::uuid()` generates a unique UUID for `user_id`.
- `Hash::make('password')` hashes the password for security.
- `now()` sets the current timestamp for `created_at` and `updated_at`.
3. **Call Seeder from DatabaseSeeder**: Open `database/seeders/DatabaseSeeder.php` and call the `UserSeeder` within the `run` method:
```php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// Call the UserSeeder
$this->call(UserSeeder::class);
}
}
```
4. **Run the Migrations and Seeders**: To ensure that your migrations and seeders run properly, you should use the following command:
```bash
php artisan migrate:fresh --seed
```
This command will drop all tables, re-run the migrations, and then seed the database with the dummy user.
### Summary
With this setup, you won't need to manually insert the dummy user each time you run `php artisan migrate:fresh`. Instead, the dummy user will be automatically inserted by the seeder. This approach is more efficient and keeps your testing process streamlined.
Comments
Post a Comment
Thank you :)