Add foreign key data Laravel in the controller

0

I have the following driver

   public function store(MachineCreateRequest $request)
{

    $user_id = auth()->id();
    $company_id = User::find($user_id)->company->id; //ID = 3
    $machine->company_id = $company_id;
    $machine = Machine::create($request->all());
    $machine->company()->attach($company_id);
    $machine->accessories()->sync($request->accessories);
    $machine->developments()->sync($request->developments);
    session()->flash('success', 'Maquina creada correctamente');
    return redirect()->route('machine.index');
}

How could I insert the $ company_id field in the Machine :: create? since when I create the record it is an error General error: 1364 Field 'company_id' does not have a default value.

    
asked by Darwin Gomez 23.01.2018 в 01:37
source

1 answer

0

How could I insert the $ company_id field in the Machine :: create?

I would need to know a little more about your database model and relationships, but according to your question, I would do the following:

public function store(MachineCreateRequest $request)
{
    $user = auth()->user();
    $company_id = $user->company['id']; //ID = 3

    // Agregar company_id al request me da a entender que existe un campo company_id en la tabla machines.
    $request->merge(['company_id' => $company_id]);
    $machine = Machine::create($request->all());

    $machine->company()->attach($company_id);
    $machine->accessories()->sync($request->accessories);
    $machine->developments()->sync($request->developments);

    session()->flash('success', 'Maquina creada correctamente');
    return redirect()->route('machine.index');
}
    
answered by 23.01.2018 в 22:43