I am using laravel 5.1. I am trying to run database seeding command.
My table name is users
My migration file is as below
2015_11_09_194832_create_users_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
DatabaseSeeder.php
<?php
use App\User;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
$this->call(UsersTableSeeder::class);
Model::reguard();
}
}
UsersTableSeeder.php
<?php
// DatabaseSeeder.php
use App\User;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
DB::table('users');
$users = array(
['name' => 'Ryan Chenkie', 'email' => 'ryanchenkie#gmail.com', 'password' => Hash::make('secret')],
['name' => 'Chris Sevilleja', 'email' => 'chris#scotch.io', 'password' => Hash::make('secret')],
['name' => 'Holly Lloyd', 'email' => 'holly#scotch.io', 'password' => Hash::make('secret')],
['name' => 'Adnan Kukic', 'email' => 'adnan#scotch.io', 'password' => Hash::make('secret')],
);
// Loop through each user above and create the record for them in the database
foreach ($users as $user)
{
User::create($user);
}
Model::reguard();
}
}
While I am trying to run seeding command php artisan db:seed I am getting below error.
[ReflectionException]
Class UsersTableSeeder does not exist
Can anyone help me in this regard ??
I've run in to this issue a few time when I've added seeders either in a new project or to an existing project where I want to add some data to test.
Both jedrzej.kurylo and Alex were on the right track, composer dump-autoload which will regenerate your autoload files and include the seeder(s) you've just added.
Related
I have a new Laravel 9 application and I am trying to use Keycloak as an SSO.
I am using this package to achieve that. I created the migrations and the seeders to have some data. I am using my own user model extending the KeycloakUser provided by the package.
My seeder does not run and I get this error message:
Call to undefined method App\Models\User::create()
My Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Vizir\KeycloakWebGuard\Models\KeycloakUser;
class User extends KeycloakUser
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'firstname',
'surname',
'email',
'role',
];
/**
* Get the company that owns the user.
*/
public function company()
{
return $this->belongsTo(Company::class);
}
/**
* Get the comments for the user.
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
}
The migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('firstname');
$table->string('surname');
$table->string('email')->unique();
$table->unsignedBigInteger('company_id')->nullable();
$table->enum('role', ['user', 'admin', 'superadmin'])->default('user');
$table->rememberToken();
$table->timestamps();
$table->foreign('company_id')->references('id')->on('companies');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
The seeder
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
User::create([
'firstname' => 'Aaaa',
'surname' => 'Bbbb',
'email' => 'ab#first.com',
'role' => 'superadmin',
]);
}
}
What you can try to do is copy KeycloakUser into app\Models.
Rename the file and class to User and than add extends Model.
namespace Vizir\KeycloakWebGuard\Models;
use Auth;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
....
// all of these methods are originated from KeycloakUser
And dont forget to adjust your config/auth.php
'providers' => [
'users' => [
'driver' => 'keycloak-users',
'model' => App\Models\User::class,
],
// ...
]
I'm running a few seeders during a migration after creating a table. Here's my migration file create_institutions_table
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateInstitutionsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('institutions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('code');
$table->timestamps();
$table->softDeletes();
});
$seeder = new InstitutionsSeeder();
$seeder->run();
$seeder2 = new UsersSeeder();
$seeder2->run();
Schema::table('users', function (Blueprint $table) {
$table->foreign('institution_id')->references('id')->on('institutions');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('institutions');
}
}
here's the InstitutionsSeeder
use Illuminate\Database\Seeder;
class InstitutionsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('institutions')->insert([
'name' => 'Institution One',
'code' => 'I1',
]);
}
}
here's the UsersSeeder
use Illuminate\Database\Seeder;
class UsersSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('users')->insert([
'first_name' => 'Admin',
'last_name' => 'Istrator',
'email' => 'admin#example.com',
'institution_id' => '1',
'password' => '$2y$10$/wYQaaaaaaagrtyh64gbdt4yuhr32l4VmFHI.sINMR/9LXsj1MTy',
]);
}
}
As far as I can tell there's no real difference between the seeders, but the migration fails when trying to instanciate the UsersSeeder class while the InstitutionsSeeder works fine. This is the exception I'm getting from the php artisan migrate:fresh command:
Symfony\Component\Debug\Exception\FatalThrowableError : Class 'UsersSeeder' not found
at H:\code\MyProject\database\migrations\2019_06_17_224612_create_institutions_table.php:27
23|
24| $seeder = new InstitutionsSeeder();
25| $seeder->run();
26|
> 27| $seeder2 = new UsersSeeder();
28| $seeder2->run();
29|
30| Schema::table('users', function (Blueprint $table) {
31| $table->foreign('institution_id')->references('id')->on('institutions');
Exception trace:
1 CreateInstitutionsTable::up()
H:\code\MyProject\vendor\laravel\framework\src\Illuminate\Database\Migrations\Migrator.php:379
2 Illuminate\Database\Migrations\Migrator::Illuminate\Database\Migrations\{closure}()
H:\code\MyProject\vendor\laravel\framework\src\Illuminate\Database\Migrations\Migrator.php:388
Please use the argument -v to see more details.
Why won't the UsersSeeder work?
Two possible solutions:
Check the namespace of your class
Run composer dump-autoload: composer dump-autoload (You can read the docs here)
Each time you create a new seeder run composer dump-autoload command.
After that just run the seeder using php artisan db:seed command.
Hope this will work !
UsersTapleSeeder.php :
<?php
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory('App\User', 50)->create();
}
}
DatabaseSeeder.php:
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
protected $toTruncate = ['users'];
public function run()
{
foreach ($this-> $toTruncate as $table)
{
DB::table('users')->truncate();
}
$this->call(UsersTableSeeder::class);
}
}
ModelFactory.php:
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
/** #var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'body' => $faker->sentences(),
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
];
});
My users table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->text('body');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
I tried migrate, migrate rollback, composer dump-autoload.
It was working until I added the body column, after that even when I delete it.
$this-> $toTruncate in your seeder is causing that error. Change it to:
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
protected $toTruncate = ['users'];
public function run()
{
foreach ($this->toTruncate as $table)
{
DB::table($table)->truncate();
}
$this->call(UsersTableSeeder::class);
}
}
I have the following:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFinanceAccountsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('finance_accounts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('created_by')->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('finance_accounts');
}
}
And the seeder:
class FinanceAccountsTableSeeder extends Seeder
{
public function run()
{
DB::table('finance_accounts')->delete();
App\Models\Finance\FinanceAccount::create([
'name' => 'Default account',
'created_by' => 1
]);
}
}
Which is called via:
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
$this->call('UserRolesTableSeeder');
$this->call('UserTableSeeder');
$this->call('FinanceTransactionsTableSeeder');
$this->call('FinanceAccountsTableSeeder');
$this->call('CurrencyTableSeeder');
$this->call('UserProfileTableSeeder');
}
}
However, the table is created fine, but no data gets inserted.
The seeders for all my other tables work perfectly, just not for this one.
Does anyone have an idea why?
namespace App\Models\Finance;
use Illuminate\Database\Eloquent\Model;
class FinanceAccount extends Model {
protected $table = 'finance_accounts';
}
I want to seed users to database but seeder doesn't create password.
I have This migration File
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('email')->unique();
$table->string('username');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
and this Seeder file
// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;
class UsersTableSeeder extends Seeder {
public function run()
{
$faker = Faker::create();
DB::table('users')->truncate();
foreach(range(1, 3) as $index)
{
$user = User::create(array(
'password' => $faker->word,
'username' => $faker->userName,
'email' => $faker->email
));
}
}
}
I did php artisan migrate and it said "nothing to migrate"
so now when I do php artisan db:seed --class=UsersTableSeeder it throws no error.
Any idea why seeder does not create username? I have just empty column in my database...
thank you very much for any help.
Try adding Eloquent::unguard(); before the start of the foreach() loop.
Also, migration (php artisan migrate command) is only concerned with running the migrations (creating the database not populating).
Alternately you can include on your DatabaseSeeder $this->call('UsersTableSeeder'); then you can run php artisan migrate --seed