Last active
December 22, 2019 17:53
-
-
Save moradi-morteza/8a19dac855e0dcdd3af274343be4f714 to your computer and use it in GitHub Desktop.
[Gate and Policy] #LaravelT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$user=auth()->user(); | |
$post=Post::where('user_id',1)->first(); | |
$allow=\Gate::allows('update-post',$post); // not need to send user it use current logined user | |
// if user not logined allow is false | |
// if you want to user another user for check a gate | |
$allow=\Gate::forUser(User::find(2))->allows('update-post',$post); | |
if($allow){ | |
// update post | |
}else { | |
// show error | |
abort(403,'nemishe'); // this show 404 page | |
} | |
// invers method of allows is deny | |
// in AuthServiceProvider.php | |
publi function boot(){ | |
$this->registerPolicies(); | |
// you can define gate:befor to check if user is superadmin then do not continue just return true | |
Gate::befor(function($user,$ability,$params){ | |
if($user->id==1) | |
return true; | |
// your code ... | |
}); | |
Gate::define('update-post',function($user,$post=null){ | |
// Gate::define('update-post',function($user,Post $post){ if you use Post it force to allows(,*) to be form Post | |
return $post->user_id===$user->id; // if be true this show that user can edit his post | |
}); | |
Gate::after(function($user,$ability,$result,$params){ | |
// your code with $result | |
}); | |
} | |
//--------------------------Example 1--------------- | |
class User extends Authenticatable | |
{ | |
use Notifiable; | |
protected $fillable = [ | |
'name', 'email', 'password','age', | |
]; | |
protected $hidden = [ | |
'password', 'remember_token', | |
]; | |
protected $casts = [ | |
'email_verified_at' => 'datetime', | |
]; | |
public function is_blocked(){ | |
if($this->status=='blocked'){return true;}else{return false;} | |
} | |
} | |
Gate::define('create-post',function($user){ | |
return $user->isblocked(); | |
}); | |
//----------------------------Example 2------------ | |
// you can send name of your model for avoid create very gate for any model | |
$allow=\Gate::allows('update-post',Post::class); | |
Gate::define('create',function($user,$model=null){ | |
if($model===User::class){...} // can create user? | |
else if($model===Tweet::class){...} // can create tweet | |
else if($model===Post::class){...} // .. | |
return false; | |
}); | |
// in blade ------------------------------------- | |
@if(auth()->user()->id===1) // or user a gate here auth()->user()->can('is-admin') | |
@else | |
@endif | |
// more than effective -------- | |
@can('is-admin') // is-admin is a gate | |
@els | |
@endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment