0

我在表单的控制器中的 store () 有问题,我在同一个控制器中生成 3 条记录,但如果最后一条记录失败,因为我错过了表单的某些字段,另外 2 条如果它们注册但我想要所有或者没有保存

 $company = new Companies;
    $company->companyName= $request->input('RazónSocial');
    $company->rfc= $request->input('rfc');
    $company->contact= "1";
    $company->street= $request->input('Calle');
    $company->extNum= $request->input('NúmeroExterior');
    $company->intNum= $request->input('NúmeroInterior');
    $company->postalCode= $request->input('CódigoPostal');
    $company->suburb= $request->input('Colonia');
    $company->city= $request->input('Ciudad');
    $company->region= $request->input('Municipio');
    $company->state= $request->input('Estado');
    $company->country= $request->input('País');
    $company->telephone= $request->input('Teléfono');
    $company->email= $request->input('Correo');
    $company->save();

    $machine = Machines::find((int)Input::get('machine'));
    $machine->companies_id = $company->id;
    $machine->save();

    $device = Devices::find($machine->device)->first();
    $device->companies_id = $company->id;
    $device->save();

    $user = New User;
    $user->name = $request->input('name');
    $user->email = $request->input('email');
    $user->companies_id = $company->id;
    $user->roles_id = 5;
    $user->avatar = "";
    $user->password = Hash::make($request->input('password'));
    $user->save();

    $company->contact = $user->id;

    if($request->Contacto == true){
        $this->validate($request,[
            'contactName' => 'required|string|max:255',
            'contactEmail' => 'required|string|email|max:255|unique:users',
            'contactPassword' => 'required|string|min:6|confirmed',
        ]);
        $contact = New User;
        $contact->name = $request->input('contactName');
        $contact->email = $request->input('contactEmail');
        $contact->companies_id = $company->id;
        $contact->roles_id = 4;
        $contact->avatar = "";
        $contact->password = Hash::make($request->input('contactPassword'));
        $contact->save();

        $company->contact = $contact->id;
    }
4

1 回答 1

4

交易。如果该功能未正确完成,则更改将不会提交到数据库。

DB::transaction(function () {

    // Database queries

});
于 2019-03-20T19:26:12.663 回答