一、下载 laravel 5.2
composer create-project laravel/laravel=5.2.* laravel5.2
新建数据库 laravel5.2
修改 .evn 配置文件
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel5.2
DB_USERNAME=laravel5.2
DB_PASSWORD=laravel5.2
修改中国时区,在 config/app.php 中修改
'timezone' => 'PRC',
二、migrations
修改 datebase/migrations/2014_10_12_000000_create_users_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
其实就是增加 username 字段
修改 database/factories/ModelFactory.php
return [
'name' => $faker->name,
'username' => $faker->userName,
'email' => $faker->safeEmail,
'password' => bcrypt(str_random(10)),
'remember_token' => str_random(10),
];
其实也是增加 username 字段
执行数据迁移
cd laravle5.2
php artisan migrate
创建测试数据
php artisan tinker
namespace App;
factory(User::class, 10)->create();
三、路由模型绑定
3.1、用户ID
修改 app/Http/routes.php
Route::get('/user/{user}', function (\App\User $user) {
return $user;
});
访问 http://localhost:8000/user/10 进行测试
3.2、用户名
修改 app/Http/routes.php
Route::get('/user/{username}', function (\App\User $user) {
return $user;
});
修改 app/Providers/RouteServiceProvider.php 的 boot 方法
public function boot(Router $router)
{
parent::boot($router);
\Route::bind('username', function($user){
return User::where('username', $user)->firstOrFail();
});
}
访问 http://localhost:8000/user/vkassulke 进行测试
注意:这里的 vkassulke 是数据库中的用户名,要根据实际的用户名进行访问