tmyers273/laravel-ownership

此包的最新版本(v1.0.0)没有提供许可证信息。

允许在路由模型绑定中进行所有权验证

v1.0.0 2019-07-06 10:07 UTC

This package is auto-updated.

Last update: 2024-09-06 22:14:50 UTC


README

一个简单的包,通过Laravel的路由模型绑定自动执行模型所有权检查。

它做什么?

// Let's whip up a few Users and a Post to demonstrate
$owner = factory(User::class)->create();
$post = factory(Post::class)->create([
    'user_id' => $owner->id
]);

$otherUser = factory(User::class)->create();
$adminUser = factory(USer::class)->create([
    'is_admin' => true
]);
// This will be a successful call, since $owner owns the $post
$this->be($owner);
$this->json('PATCH', '/post/' . $post->id, [
    'title' => 'Edited by Owner'
]);
// This will fail, since $otherUser does not own the $post
$this->be($otherUser);
$this->json('PATCH', '/post/' . $post->id, [
    'title' => 'Edited by Owner'
]);
// This will be a successful call, since $adminUser can override the ownership check (by default)
$this->be($adminUser);
$this->json('PATCH', '/post/' . $post->id, [
    'title' => 'Edited by Owner'
]);
// This will fail, since 12345 is a made up Post id
$this->be($owner);
$this->json('PATCH', '/post/12345', [
    'title' => 'Edited by Owner'
]);

安装

composer require tmyers273/laravel-ownership

php artisan vendor:publish --tag=laravel-ownership-config --tag=laravel-ownership-trait

OwnsModels 特性添加到您的 User 模型

use App\Traits\OwnsModels;

class User extends Authenticatable
{
    use OwnsModels;
}

OwnedByUser 添加到您想要验证所有权的每个模型。

use TMyers273\Ownership\OwnedByUser;

class Post extends Model
{
    use OwnedByUser;
}

修改 OwnsModels 特性中的 isAdminowns 方法以满足您的需求!