GuilhermeSO
GuilhermeSO

Reputation: 89

How to make a Edit after making the Create

Im doing a crud for my Vue/Laravel application, my add button is working fine but im having trouble making work my edit/update button. I dont get any erros from backend or frontend, just dont work This is my code:

Frontend:

async addDespesa() {
  let uri = "api/despesas";
  const response = await axios.post(uri, this.despesa).then((response) => {
    this.despesas.push({
      des: this.despesa.des,
      valr: this.despesa.valr,
      stt: this.despesa.stt,
      vencc: this.despesa.vencc,
      emiss: this.despesa.emiss,
    });
    this.despesa.des = "";
    this.despesa.valr = "";
    this.despesa.vencc = "";
    this.despesa.stt = "";
    this.despesa.emiss = "";
    this.getDespesa();
  });
},

 async updateDespesa() {
  let uri = `api/despesas/{despesa}/edit`;
  const response = await axios.get(uri, this.despesa).then((response) => {
   this.despesas.push({
      des: this.despesa.des,
      valr: this.despesa.valr,
      stt: this.despesa.stt,
      vencc: this.despesa.vencc,
      emiss: this.despesa.emiss,
    });
    this.despesa.des = "";
    this.despesa.valr = "";
    this.despesa.vencc = "";
    this.despesa.stt = "";
    this.despesa.emiss = "";
    this.getDespesa();
  });
},

Backend:

public function edit($id)
{
  $despesa = Despesa::find($id);
  return response()->json($despesa);
}

public function update($id, Request $request)
{
  $despesa = Despesa::find($id);

  $despesa->update($request->all());

  return response()->json('Sucess');
}

Upvotes: 0

Views: 53

Answers (1)

JoeGalind
JoeGalind

Reputation: 3815

I usually recycle the update function for both store and update.

public function store(Request $request) {
    return $this->update($request, 0);
}

public function update(Request $request, $id) {
    if ($id == 0) {
        $despesa = new Despesa;
    }
    else {
        $despesa = Despesa::findOrFail($id);
    }

    $despesa->update($request->all());

    return response()->json('Sucess');
}

Also, check the order of the params for the update function. Request first and id second

Upvotes: 1

Related Questions