* 注意:我的策略在技术上可能是“不正确的”,因为它污染了全局命名空间。但是,我无法让其他答案正常工作,并且仅作为最后的手段发布。 *
我这样做的方式与其他答案略有不同。我也在使用 Laravel 5。
1) 我创建了 app/Models 目录并将 User.php 移到该目录中。
2) 我通过删除顶部的命名空间来修改 /app/Models/User.php。这可能会污染全局命名空间,但这是我让它工作的唯一方法。
<?php // !!!! NOTICE no namespace here !!!!!
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 = ['first_name', 'last_name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
}
3) 我在 composer.json 的自动加载部分添加了“app/Models”:
"autoload": {
"classmap": [
"database",
"app/Models" // <==== I added this
],
"psr-4": {
"App\\": "app/"
}
},
4)我修改auth.php如下:
/*
|--------------------------------------------------------------------------
| Authentication Model
|--------------------------------------------------------------------------
|
| When using the "Eloquent" authentication driver, we need to know which
| Eloquent model should be used to retrieve your users. Of course, it
| is often just the "User" model but you may use whatever you like.
|
*/
'model' => '\User',
作为参考,这是我的 users 表迁移:
<?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('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
这是我的 UsersTableSeeder.php 文件:
<?PHP
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class UsersTableSeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
$users = [
[ 'id' => 1, 'first_name' => 'Bret', 'last_name' => 'Lastname', 'email' => 'email@domain.com', 'password' => Hash::make('my raw dev password')]
];
foreach($users as $user){
\User::create($user);
}
}
}
?>
完成所有这些更新后,我在命令行上运行:
composer dump-autoload
php artisan migrate --seed
希望这会有所帮助!