santigarcor / laravel-ownable
简单的 trait,用于管理模型/对象的拥有权
1.0.3
2023-12-18 19:31 UTC
Requires
- illuminate/database: ^6.0|^7.0|^8.0|^9.0|^10.0
- illuminate/support: ^6.0|^7.0|^8.0|^9.0|^10.0
- laravel/legacy-factories: ^1.3
Requires (Dev)
- orchestra/testbench: ^4.0|^5.0|^6.0
- phpunit/phpunit: ^7.5.15|^8.4|^9.0
This package is auto-updated.
Last update: 2024-09-18 20:59:38 UTC
README
此 trait 允许你在 Laravel 应用程序中检查一个模型是否拥有其他模型。
安装
简单运行
composer require santigarcor/laravel-ownable
然后,你需要在想要检查是否拥有其他模型的模型中使用 OwnsModels
trait。
<?php use Ownable\OwnsModels; use Illuminate\Database\Eloquent\Model; class User extends Model { use OwnsModels; }
你现在可以使用它了。
使用方法
<?php use Ownable\OwnsModels; use Illuminate\Database\Eloquent\Model; class User extends Model { use OwnsModels; } class Video extends Model { } $user = User::first(); $video = Video::first(); // Check If the user owns the video if ($user->owns($video)){} // Check If the user doesn't owns the video if ($user->doesntOwn($video)){} // Check If the user owns the video but the foreign key is the_user_id if ($user->owns($video, 'the_user_id')){}
如果出于某种原因,所有权检查需要更复杂的逻辑,你可以在你的拥有权对象内部实现 Ownable
接口,然后你可以在 isOwnedBy
方法中定义自定义逻辑。当此方法被调用时,调用 owns
方法的对象被作为属性传递给 isOwnedBy
方法。
<?php use Ownable\OwnsModels; use Illuminate\Database\Eloquent\Model; class User extends Model { use OwnsModels; } use Ownable\Contracts\Ownable; class Video extends Model implements Ownable { public function isOwnedBy($owner): bool { if ($owner instanceof User) { return $this->someRelationship->user_id == $owner->id; } return false; } } $user = User::first(); $video = Video::first(); // Then you can simply call the owns method on the user and it will work. // Check If the user owns the video if ($user->owns($video)){} // Check If the user owns the video but don't use the ownable logic, instead the regular one with the foreign key. if ($user->owns($video, null, false)){}