Skip to content

Commit

Permalink
Merge pull request #74 from RonasIT/62-fix-unique-except-of-authorize…
Browse files Browse the repository at this point in the history
…d-user-major

fix: unique_except_of_authorized_user fails when value is array
  • Loading branch information
DenTray authored Jun 20, 2023
2 parents e24b287 + 7415b45 commit 9f750cc
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/HelpersServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\ExcelServiceProvider;
use RonasIT\Support\Middleware\SecurityMiddleware;
use Illuminate\Support\Arr;

class HelpersServiceProvider extends ServiceProvider
{
Expand All @@ -18,11 +19,17 @@ public function boot()
$router->prependMiddlewareToGroup('web', SecurityMiddleware::class);
$router->prependMiddlewareToGroup('api', SecurityMiddleware::class);

Validator::extend('unique_except_of_authorized_user', function ($attribute, $value) {
validator::extend('unique_except_of_authorized_user', function ($attribute, $value, $parameters = []) {
$table = Arr::get($parameters, 0, 'users');
$keyField = Arr::get($parameters, 1, 'id');
$userId = app(JWTAuth::class)->toUser()->id;
$result = DB::select("select count(*) as entities_count from users where id <> {$userId} and {$attribute} = '{$value}';");

return $result[0]->entities_count == 0;
$result = DB::table($table)
->where($keyField, '<>', $userId)
->whereIn($attribute, Arr::flatten((array) $value))
->exists();

return !$result;
});

app(ExcelServiceProvider::class, ['app' => app()])->boot();
Expand Down

0 comments on commit 9f750cc

Please sign in to comment.