這篇文章主要轉載於http://www.zhoujiping.com/new-in-laravel-5/gate.html
先做些準備工作, 先建立一個posts
的migration文件並運營migrate, 內容如下:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
到ModelFactory.php寫上我們需要的測試數據:
$factory->define(App\Post::class, function (Faker\Generator $faker) {
return [
'user_id' => factory(App\User::class)->create()->id,
'title' => $faker->sentence,
'body' => $faker->paragraph
];
});
打開php artisan tinker, 生成一個posts表的測試數據
Psy Shell v0.8.0 (PHP 7.0.12 — cli) by Justin Hileman
>>> factory(App\Post::class)->create();
=> App\Post {#695
user_id: 1,
title: "Qui adipisci laboriosam qui mollitia quia.",
body: "Iusto omnis libero fuga quibusdam. Cum id id libero et necessitatibus ea. Officiis laboriosam occaecati aut.",
updated_at: "2016-12-24 06:01:31",
created_at: "2016-12-24 06:01:31",
id: 1,
}
>>> App\User::first();
=> App\User {#702
id: "1",
name: "Ms. Emelia Dooley",
email: "[email protected]",
created_at: "2016-12-24 06:01:31",
updated_at: "2016-12-24 06:01:31",
}
>>>
我們生成了posts的一條記錄,同時也生成了對應的User。我們再去生成一個PostsController.php的控制器
php artisan make:controller PostsController
寫個資源路由:
Route::resource('posts', 'PostsController');
我們在控制器中寫一個顯示某個具體帖子的方法show($id)
class PostsController extends Controller
{
public function show($id)
{
$post = Post::findOrFail($id);
return $post->title;
}
}
瀏覽器訪問: http://localhost:8000/posts/1
針對這個問題,laravel給了我們提供了Gates和Policies兩種方案,我們先來看第一種Gates怎麼用(以後我們可以看下laravel是怎麼實現這個功能的)要使用Gate, 那我們首先需要去定義(註冊)一個Gate,涉及到與註冊相關的概念,我們肯定會想到服務提供者Provider, 到app/Providers/AuthServiceProvider.php中,將我們需要的Gate定義在boot()方法中,爲什麼要放這裏,前面的文章已經講解的非常清楚了。
public function boot()
{
$this->registerPolicies();
// 這裏的$user是當前登錄用戶,laravel會處理
// 在調用的時候不用傳入
Gate::define('show-post', function ($user, $post)) {
return $user->id == $post->user_id;
}
}
上面代碼優化下,方便複用
public function boot()
{
$this->registerPolicies();
// 這裏的$user是當前登錄用戶,laravel會處理
// 在調用的時候不用傳入
Gate::define('show-post', function ($user, $post)) {
return $user->owns($post);
}
}
/** 在User.php中 */
public function owns($related)
{
return $this->id == $related->user_id;
}
定義好後,就能按下面這樣調用了
public function show($id)
{
auth()->loginUsingId(1);
$post = Post::findOrFail($id);
if (Gate::denies('show-post', $post)) {
abort(403, 'Sorry, not sorrry.');
}
return $post->title;
}
本節都這裏結束.