所以我在迁移数据库后尝试了一个基本php artisan db:seed
,但它在cmd - [Symfony'Component'Debug'Exception'FatalErrorException] Class 'User' not found
中不断返回标题错误
我尝试过的事情
- 更新类后的 PHP 转储自动加载
- 运行
db:seed
函数之前的 php dump-autoload - 回滚迁移,然后重新运行它
- 回滚迁移,然后使用
--seed
语法重新运行它 - 更改"用户"文件的命名空间
以下是迁移
<?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');
}
}
我相信这里的一切都是正确的,现在这里是用户类。
<?php namespace App;
use Illuminate'Auth'Authenticatable;
use Illuminate'Database'Eloquent'Model;
use Illuminate'Auth'Passwords'CanResetPassword;
use Illuminate'Contracts'Auth'Authenticatable as AuthenticatableContract;
use Illuminate'Contracts'Auth'CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
}
现在最后是最重要的数据库播种机
<?php
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('UserTableSeeder');
$this->call('UserTableSeeder');
Model::reguard();
}
}
class UserTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->delete();
User::create(['email' => 'John@doe.com']);
}
}
这就是我的完整语法,如果需要更多文件,请请求它们,我将更新我的问题。
在根命名空间的DatabaseSeeder
中,您调用类User
。因此,它尝试加载类User
。但是,类User
的定义在命名空间App
中。因此,您应该在DatabaseSeeder
中使用App'User
或在文件顶部添加use App'User;
DatabaseSeeder
<?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('UserTableSeeder');
$this->call('UserTableSeeder');
Model::reguard();
}
}
class UserTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->delete();
User::create(['email' => 'John@doe.com']);
}
}
由于Laravel 8+,User类现在默认存储在app/Models
目录中;因此不使用App'User
使用上面的App'Models'User
。
Ps. 默认情况下,Laravel附带一个用户模型,请使用该模型。如果您删除了该模型,则可以使用Laravel提供的回退:
use Illuminate'Foundation'Auth'User;
附带说明一下,我发现一些东西对于调试工匠输出非常有用。您应该使用标志-vvv
,它为输出消息(包括完整的堆栈跟踪)增加了极端冗长。
php artisan migrate -vvv