Authorization ve Policies
Authorization, kullanıcının belirli eylemleri yapıp yapamayacağını kontrol eder.
Gates
// AppServiceProvider boot() içinde
use Illuminate\Support\Facades\Gate;
Gate::define('update-post', function ($user, $post) {
return $user->id === $post->user_id;
});
Gate::define('admin', function ($user) {
return $user->role === 'admin';
});
// Kullanım
if (Gate::allows('update-post', $post)) {
// İzin var
}
if (Gate::denies('update-post', $post)) {
// İzin yok
}
// Controller'da
$this->authorize('update-post', $post);
// Blade'de
@can('update-post', $post)
Düzenle
@endcan
@cannot('update-post', $post)
Düzenleme yetkiniz yok
@endcannot
Policies
php artisan make:policy PostPolicy --model=Post
isAdmin()) {
return true;
}
return null; // Diğer kontrollere devam
}
/**
* Listeleme
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Tek kayıt görüntüleme
*/
public function view(User $user, Post $post): bool
{
return $post->status === 'published'
|| $user->id === $post->user_id;
}
/**
* Oluşturma
*/
public function create(User $user): bool
{
return $user->hasVerifiedEmail();
}
/**
* Güncelleme
*/
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
/**
* Silme
*/
public function delete(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
}
// Controller'da kullanım
public function edit(Post $post)
{
$this->authorize('update', $post);
return view('posts.edit', compact('post'));
}
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
// ...
}
// Resource Controller'da otomatik
public function __construct()
{
$this->authorizeResource(Post::class, 'post');
}
// Blade'de
@can('update', $post)
Düzenle
@endcan
@canany(['update', 'delete'], $post)
...
@endcanany
Önemli Noktalar
- Gate'ler basit yetki kontrolleri için
- Policy'ler model bazlı yetkilendirme için
- can() metodu ile yetki kontrolü
- @can direktifi Blade'de kullanılır
- authorize() metodu controller'da exception fırlatır