生成 3 条记录或 none Laravel 控制器

Generate 3 record or none Laravel Controller

我在表单控制器中的存储 () 有问题,我在同一个控制器中生成 3 条记录,但如果最后一条记录失败,因为我错过了表单的某些字段,如果其他 2 条记录注册,但我希望所有或 none 都被保存

 $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;
    }

transactions。如果功能没有正确完成,更改将不会提交到数据库。

DB::transaction(function () {

    // Database queries

});