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

时间:2019-03-20 19:02:21

标签: laravel eloquent laravel-controller

我在窗体的控制器中的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;
    }

1 个答案:

答案 0 :(得分:4)

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

DB::transaction(function () {

    // Database queries

});