一、下载 laravel 5.1
composer create-project laravel/laravel=5.1.* laravel5.1_rbac
新建数据库 laravel5.1_rbac
修改 .evn 配置文件
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel5.1_rbac
DB_USERNAME=laravel5.1_rbac
DB_PASSWORD=laravel5.1_rbac
修改中国时区,在 config/app.php 中修改
'timezone' => 'PRC',
切换目录
cd laravel5.1_rbac
二、数据准备
创建迁移文件
php artisan make:migration create_posts_table --create=posts
修改生成的迁移文件
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->text('content');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
执行数据迁移
php artisan migrate
生成 post 模型
php artisan make:model Post
生成测试数据
修改 database/factories/ModelFactory.php
$factory->define(App\Post::class, function (Faker\Generator $faker) {
return [
'user_id' => factory(\App\User::class)->create()->id,
'title' => $faker->sentence,
'content' => $faker->paragraph,
];
});
进入 tinker
php artisan tinker
创建文章
factory('App\Post')->create();
生成用户
factory('App\User')->create();
三、authorize
app/User.php 新增方法
public function owns($post)
{
return $this->id == $post->user_id;
}
修改 app/Providers/AuthServiceProvider.php
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
$gate->define('show-post', function($user, $post){
return $user->owns($post);
});
}
生成控制器
php artisan make:controller PostsController
修改生成的文件:app/Http/Controllers/PostsController.php
public function show($id)
{
$post = Post::findOrFail($id);
\Auth::loginUsingId(2);
$this->authorize('show-post', $post);
return $post->title;
}
注册路由:修改 app/Http/routes.php
Route::resource('posts', 'PostsController');
打开服务
php artisan serve
访问:http://localhost:8000/posts/1
修改:app/Http/Controllers/PostsController.php,登录 id=1 的用户
public function show($id)
{
$post = Post::findOrFail($id);
\Auth::loginUsingId(1);
$this->authorize('show-post', $post);
return $post->title;
}
发现正常返回
四、@can
修改:app/Http/Controllers/PostsController.php
public function show($id)
{
$post = Post::findOrFail($id);
\Auth::loginUsingId(2);
return view('posts.show', compact('post'));
}
新建视图:resources/views/posts/show.blade.php
{{ $post->title }}
@can('show-post', $post)
编辑文章
@endcan
访问:http://localhost:8000/posts/1,发现没有编辑按钮
修改:app/Http/Controllers/PostsController.php,登录 id=1 的用户
public function show($id)
{
$post = Post::findOrFail($id);
\Auth::loginUsingId(1);
return view('posts.show', compact('post'));
}
访问:http://localhost:8000/posts/1,发现有编辑按钮