eggplantSword's avatar

try catch making my model not save

I'm not sure what's happening with this but when I try this

    public function store(PopWarehouseRequest $request)
    {
        DB::beginTransaction();

        try {
            $request->write();

            return redirect('pop-helper/warehouses')->with('success', 'Bodega registrada correctamente.');
        } catch (Exception $e) {
            Log::error($e);
            DB::rollBack();

            return redirect('pop-helper/warehouses')->withErrors('Hubo un error al intentar registrar la bodega.', 'notification');
        }
    }

Nothing happens, as in no errors and no model being saved. if I try this it saves no problem.

    public function store(PopWarehouseRequest $request)
    {
            $request->write();

            return redirect('pop-helper/warehouses')->with('success', 'Bodega registrada correctamente.');
    }

This is my custom request file

public function rules()
    {
        if ($id = request()->route('id', false)) {
            $rules['name'] = ['required', 'string',
                Rule::unique(Warehouse::class)->when($id, fn($rule) => $rule->ignore($this->route('id')))];
        } else {
            $rules['name'] = 'required|string|unique:warehouses';
        }

        $rules['pop_campaign'] = 'string|nullable';

        return $rules;
    }

    public function attributes()
    {
        return ['name' => 'Nombre'];
    }

    public function write()
    {
        $warehouse = Warehouse::create($this->all());

        if ($this->request->has('pop_campaign'))
            $warehouse->popCampaign()->attach($this->pop_campaign);
    }

    public function rewrite()
    {
        $warehouse = Warehouse::query()->findOrFail($this->route('id'));
        $warehouse->fill($this->all());
        $warehouse->save();

        if ($this->request->has('pop_campaign'))
            $warehouse->popCampaign()->sync(Arr::wrap($this->pop_campaign));
    }

is there a way to do this correctly where I still keep the try/catch?

0 likes
2 replies
click's avatar
click
Best Answer
Level 35

When you start a database transaction you should close it with a commit

\DB:: beginTransaction(); 
try {
   // do something

   \DB::commit();
} catch (\Exception $e) {
   \DB:: rollBack(); 
}

Or use the closure callback which does this for you:

\DB::transaction(function(){
     // do something
});

See the docs: https://laravel.com/docs/10.x/database#database-transactions

eggplantSword's avatar

@click omg... I have this same setup all over my files (correctly) too this one wasn't working and I was lost

Please or to participate in this conversation.