johncarter
5 months ago
302
2
Laravel

Refactor Saving Many to Many Relationship

Posted 5 months ago by johncarter

I know this can be refactored into something beautiful but don't have enough skill to know how to do it.

Would someone be able to help me get this code block looking a bit shorter and more readable?

    // [email protected]

    // $request->get('services') :
    // "services" = [
    //   "service_handle",
    //   "another_service_handle"
    // ]

    $serviceIds = [];
    if ($request->has('services')) {
      foreach ($request->get('services') as $maybeNewService) {
        $existingService = Service::where('handle', $maybeNewService)->first();
        if ($existingService) {
          $serviceIds[] = $existingService->id;
        } else {
          $newService = Service::create([
            'handle' => $maybeNewService,
            'name' => ucwords(str_ireplace('_', ' ', $maybeNewService)),
          ]);
          $serviceIds[] = $newService->id;
        }
      }
    }

    $booking->services()->sync($serviceIds);

Please sign in or create an account to participate in this conversation.