Как разделить запрос тела на два объекта (jSON API) - PullRequest
0 голосов
/ 29 марта 2019

Я хочу разделить свой JSON (Body Request) на два объекта, например:

{
    "user_profile": {
        "email": "shahzad@ovadamd.com",
        "password": "admin123",
        "password_confirmation": "admin123",
        "status": 0,
        "first_name": "Shahzad",
        "middle_name": "Hussain",
        "last_name": "Shah",
        "date_of_birth": "2015-01-01",
        "gender": "M",
        "area_id": 1,
        "address": "Minhatten NY",
        "city": "New York",
        "state": "Washington",
        "zip": "12312",
        "fax": "111-111-1111",
        "phone_extension": "2471",
        "work_phone": "111-111-1111",
        "phone_no": "111-111-1111",
        "emergency_contact": "111-111-1111",
        "social_security": "111-11-1111",
        "module_id": 2,
        "role_id": 1
    },
    "prev": {
        "speciality_id": 1,
        "facility_id": 1,
        "priv_title": "can edit doctor",
        "priv_key": "ced",
        "display_group": "Doctor",
        "prev_id" :1
    }
}

Мой контроллер, в котором я создал два массива:

$body = $request->all();

$userProfile = $body['user_profile'];
$userPrev = $body['prev'];

$bodyObj = array_merge($userProfile, $userPrev);
$bodyObj['token'] = $body['token'];

и весь мой код контроллера:

public function register(Request $request) {
    $body = $request->all();

    $userProfile = $body['user_profile'];
    $userPrev = $body['prev'];

    $bodyObj = array_merge($userProfile, $userPrev);
    $bodyObj['token'] = $body['token'];

    $validator = UserValidations::validateUser($bodyObj);

    if ($validator->fails()) {
        return response([
            'status' => false,
            'message'   => __('messages.validation_errors'),
            'errors' => $validator->errors()->all()
        ], 200);
    }

    DB::beginTransaction();

    try{

        $token = JWTAuth::getToken();
        $apy = JWTAuth::getPayload($token)->toArray();
        $request->merge(['module_id' => $apy['module_id']]);
        $request->request->add(['created_by' => Auth::user()->id]);
        $request->merge(['password' =>  bcrypt($request->input('password'))]);
        $user = $this->user->create($request->only($this->user->getModel()->fillable));
        $request->request->add(['user_id' => $user->id]);
        $this->userBasicInfo->create($request->only($this->userBasicInfo->getModel()->fillable));
        $this->userContactDetails->create($request->only($this->userContactDetails->getModel()->fillable));
        $this->userAccessModule->create($request->only($this->userAccessModule->getModel()->fillable));
        $this->userRoles->create($request->only($this->userRoles->getModel()->fillable));
        $this->verifyUser->create(['user_id' => $user->id, 'token' => str_random(40)]);

        $this->userSpeciality->create($request->only($this->userSpeciality->getModel()->fillable));
        $this->userFacility->create($request->only($this->userFacility->getModel()->fillable));
        $this->userDefinition->create($request->only($this->userDefinition->getModel()->fillable));
        $this->userPrev->create($request->only($this->userPrev->getModel()->fillable));


        Mail::to($user->email)->send(new VerifyMail($user));

        DB::commit();

        return response([
            'status' => true,
            'message' => 'User registered successfully',
        ], 200);

    } catch(\Exception $ex) {
        DB::rollback();
        return response([
            'status' => false,
            'message' => __('messages.validation_errors'),
            'errors' => $ex->getMessage(),
        ], 500);
    }
}

когда я нажму этот API, я получил непредвиденную ошибку

"ошибки": "SQLSTATE [23000]: нарушение ограничения целостности: 1452 Невозможно добавить или обновить дочернюю строку: ограничение внешнего ключа не выполнено (frontdesk. user_roles, ОГРАНИЧЕНИЕ user_roles_role_id_foreign ИНОСТРАННЫЙ КЛЮЧ (role_id) ССЫЛКИ roles (id) НА УДАЛЕННОМ КАСКАДЕ) (SQL: вставить в user_roles (user_id, updated_at, created_at) значения (5, 2019-03-29 19:01:15, 2019-03-29 19:01:15)) "

когда я удаляю их функции arrry_merge и делаю запросы тела в один объект, он отлично работает: я просто хочу разделить мой запрос тела на два объекта:

Ваша помощь нужна:

...