Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Duplicate device name validation #163

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions app/Http/Controllers/Web/DevicesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
use Illuminate\Http\Request;
use Illuminate\View\View;
use Webpatser\Uuid\Uuid;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Validator as BaseValidator;

class DevicesController extends Controller
{
Expand Down Expand Up @@ -38,6 +40,12 @@ public function add(Request $request): RedirectResponse
{
$properties = $request->all();
$currentUserId = $request->user()->id;

$validator = $this->validateDuplicateName($properties, $currentUserId);
if ($validator->fails()) {
return $this->redirectToDevicesWithMessage($request, FlashMessageLevels::DANGER, 'Cannot create device with duplicate name!');
}

$device = $this->deviceRepository->create($properties, $currentUserId);
$name = $device->name;

Expand Down Expand Up @@ -75,6 +83,12 @@ public function update(Request $request, Uuid $publicDeviceId): RedirectResponse
}

$properties = $request->all();
$currentUserId = $request->user()->id;

$validator = $this->validateDuplicateName($properties, $currentUserId);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This chunk of code appears to be identical to the one above when creating a device except for the verb in the flash message. Please consider making a private method with some parameter to prevent repeating this block of code.

if ($validator->fails()) {
return $this->redirectToDevicesWithMessage($request, FlashMessageLevels::DANGER, 'Cannot update device with duplicate name!');
}

$device = $this->deviceRepository->update($deviceId, $properties);

Expand Down Expand Up @@ -102,4 +116,13 @@ private function redirectToDevicesWithMessage(Request $request, string $flashLev

return redirect()->route('devices');
}

private function validateDuplicateName(array $properties, int $currentUserId): BaseValidator
{
$validator = Validator::make($properties, [
'name' => 'unique:devices,name,null,null,user_id,' . $currentUserId
]);

return $validator;
}
}