Gabriel Sassaki
Gabriel Sassaki

Reputation: 133

How to save and update at the same time with laravel and vue

I'm having a problem that I couldn't find an answer in anywhere yet. I'm writing an app with PHP(Laravel) in the backend and VueJs in the frontend. I've managed to do the entire application with no much problem but now, I have to save and update one table at the same time, i'll explain following the code.

Scenario Update

I'm writing a maintenance control, i have to input records of maintenances in a table so, there are some maintenances that are made periodically and i'm supposed to warn when the next maintenance is comming, that's why i need to POST and Put at the same time. I can't send a single request from vue to laravel because i'm using routes and, if it goes with the POST method, i get method not allowed error, as you can see in the controller's function, i already tried to use a single request.

Here's the routes that i'm using in a main vue file:

<b-tab title="Cadastro de Manutenções">
                    <manutencao-cadastro
                        rotacadadd="manutencao/cadastro/"
                        rotamaquina="manutencao/cadastro/autcomp"
                        rotatipoautcomp="manutencao/cadastro/axios-tipo"
                        rotanomecolaborador="manutencao/cadastro/nomeColaborador"
                        rotacadsalvar="manutencao/cadastro/salvarManutencao"
                        rotacadatualizar="manutencao/cadastro/updateManute"
                        rotacaddel="manutencao/cadastro/deleteManute"
                        rotaatualizacadastro="manutencao/cadastro/atualizaCad"
                    />
                </b-tab>

Here's my function to save/update on vue:

save(){
            const method = this.maintenance.id ? 'put' : 'post'
            const id = this.maintenance.id ? `/${this.maintenance.id}` : ''
            const url = this.maintenance.id ? this.rotacadatualizar : this.rotacadsalvar
            axios[method](`${url}${id}`, this.maintenance)
                .then(() => {
                    this.reset()
                }).catch((err) => {
                console.error(err)
            });
    }

As you can see, this function saves or updates depending on the case, working normally.

This is my function at the backend:

public function saveMaintenance(Request $request)
{

    $maquina = $this->ManutencaoMaquinasM
        ->where('descricao', $request->maquina)
        ->first();

    $tecnico = $this->ColaboradorM
        ->where('nomecolaborador', $request->tecnico)
        ->first();

    $manutencao = $this->TecManutencaoTipoM
        ->where('manutencao', $request->manutencao)
        ->first();

    $dia = '';

    $data = $this->TecManutencaoCadastroM->join('manutencao_maquinas', 'tec_manutencao_cadastros.maqId', 'manutencao_maquinas.id')
        ->select(DB::raw('max(tec_manutencao_cadastros.data) as date'))
        ->where('manutencaoId', $manutencao->id)
        ->where('manutencao_maquinas.descricao', $request->maquina)
        ->get();

    foreach ($data as $dat) {
        $dia = $dat->date;
    }

    try{
        \DB::beginTransaction();
        $input = $request->all();

        $maintenance = new TecManutencaoCadastro();
        $maintenance->maqId = $maquina->id;
        $maintenance->tipoId = $input['tipo'];
        $maintenance->manutencaoId = $manutencao->id;
        $maintenance->tecnicoId = $tecnico->id;
        $maintenance->data = $input['data'];
        $maintenance->tempo = $input['tempo'];
        $maintenance->obs = $input['obs'];
        $maintenance->save();

        /* $atualizar = $this->TecManutencaoCadastroM
            ->where('madIq', $maquina->id)
            ->where('manutencaoId', $manutencao->id)
            ->where('data', $dia)
            ->update(array('atendido' => 's')); */

        //\Log::info($maintenance);

        \DB::commit();

        return response()->json('salvo', 200);

    } catch (\Exception $e){
        \DB::rollback();
        return response()->json($e.'erro', 422);
    }
}

Also working fine when I have to save the data. The commented block works in laravel but with in vue, it doesn't.

This is the function to update:

public function updateMaintenance(Request $request)
{
    $maquina = $this->ManutencaoMaquinasM
        ->where('descricao', $request->maquina)
        ->first();

    $tecnico = $this->ColaboradorM
        ->where('nomecolaborador', $request->tecnico)
        ->first();

    $manutencao = $this->TecManutencaoTipoM
        ->where('manutencao', $request->manutencao)
        ->first();

    try{
        \DB::beginTransaction();

        $tipo = $this->TecManutencaoCadastroM->where('id', '=', $request->id)
            ->update(
                array(
                    'maqId' => $maquina->id,
                    'tipoId' => $request->tipo,
                    'manutencaoId' => $manutencao->id,
                    'tecnicoId' => $tecnico->id,
                    'data' => $request->data,
                    'tempo' => $request->tempo,
                    'obs' => $request->obs
                )
            );


        \DB::commit();

        return response()->json('salvo', 200);

    } catch (\Exception $e){
        \DB::rollback();
        return response()->json($e.'erro', 422);
    }
}

Working as suposed to do.

My problem is, I'm trying to save some new data in the table and update another row in the same table, in the same time, but as you can see in the vue method, when I save, the path points to POST and when I update, the path points to PUT, I guess that's why i'm not able to do this action. Is that a way for me to do this? I'm new on vue and didn't find anything that could help me. Can anyone point me some directions please?

Thanks in advance.

Upvotes: 1

Views: 1278

Answers (1)

waterloomatt
waterloomatt

Reputation: 3742

The way I see it you have 2 options. Either initiate 2 separate requests (at the same time) OR send a single request and let PHP figure out how to handle both the insert and the update.

Not sure what the difference between TecManutencaoCadastro and TecManutencaoCadastroM is so I just copied/pasted it from your example.

Scenario 1: Send 2 requests

Keep both your saveMaintenance and updateMaintenance PHP methods, and initiate a single request for each one. Ex. Axios-Make multiple request at once (vue.js)

axios.all([
    this.make_post_request(),
    this.make_put_request()
])
...
make_post_request() {
    return axios.post('...url...', { params: 'example' })
},
make_put_request() {
    return axios.put('...url...', { params: 'example' })
}
...

Scenario 2: Make a single (post) request

Pass all your data along with the request and let PHP determine what to do with it. This scenario just expands the post (insert) functionality to handle your specific use-case of also updating the prior maintenance record if it exists.

save(){
    axios['post'](`...url...`, this.maintenance)
        .then(() => {
            ...
        })
    );
}

PHP

public function saveMaintenance(Request $request)
{
    // Begin transaction

    // The request has an `id` parameter so do the update to set the status to `s`.
    if ($request->has('id')) {
        $tipo = $this->TecManutencaoCadastroM->where('id', '=', $request->id)
            ->update(
                ...
            );                
    }

    // Finally, create the new maintenance row with value `n`.
    $maintenance = new TecManutencaoCadastro();
    ...
    $maintenance->save();

    // Commit transaction
}

You should keep updateMaintenance for when you want to actually issue a put request to update a maintenance record.

Upvotes: 1

Related Questions