01:Laravel ACL 权限
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->text('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
$factory->define(App\Post::class, function (Faker\Generator $faker) {
return [
'user_id' => factory(\App\User::class)->create()->id,
'title' => $faker->sentence,
'body' => $faker->paragraph,
];
});
public function show($id)
{
$post = Post::findOrFail($id);
return $post->title;
}
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
##判断这篇文章是否当前用户创建
$gate->define( 'show-post',function( $user,$post ) {
return $user->id == $post->user_id;
});
}
找到控制器show方法【跟视频的版本有出入,到此步出错,mark,我用的是:Laravel Framework version 5.1.45 (LTS)
】,修改如下,修改后第一种方案后,效果同视频一致,第二种方案是正常的
use Illuminate\Contracts\Auth\Access\Gate as GateContract;//引用
class PostsController extends Controller
{
protected $authCheck;//增加
//增加
public function __construct( GateContract $gate )
{
$this->authCheck = $gate;
}
public function show($id)
{
$post = Post::findOrFail($id);
\Auth::loginUsingId(2);
//$this->authorize( 'show-post',$post );#第二种方式
if( !$this->authCheck->check( 'show-post',$post ) ) {
abort( 403,'Sorry' );
}
return $post->title;
}
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
##判断这篇文章是否当前用户创建
$gate->define( 'show-post',function( $user,$post ) {
return $user->owns( $post );
});
}
public function owns($post)
{
return $this->id == $post->user_id;
}