I want to use axios to flip the DB value every time I click it asynchronously.

Asked 2 years ago, Updated 2 years ago, 143 views

I'm using Ravel and vue to create a TODO app, and I don't know how to implement it (using axios to flip DB values every time I click on them), or even if DB doesn't have a true value in the done column, I'll let vue have only the true value of done.
The fifth line of the image contains click events.The click event method has not been written yet.
Like the TODO task on the first page, if you click on the circle on the left, it becomes a checked circle, and the color of the element changes, and if you click on it again, it will be restored.The TODO in the image is made only by vue, but if you include Ravel, the title and ID of the task are registered in DB and displayed in Vue. I don't know if Vue will manage the completion status or DB, so I would like someone to tell me how to implement it.
Vue component in Task View
TODO"src="https://i.stack.imgur.com/Zxuvn.png"/>

made with vue.js laravel-5 asynchronous axios

2022-09-30 14:30

1 Answers

First of all, I think it's better to write a code instead of SS.And SS can only see the contents of the template.For example, I'd like to see what's going on in the toggleDone() method. Would you like me to imagine what I still want to do and write something as a sample?

You don't seem to want to use Checkbacks, so let's think of a way without a v-model.

template

@click="toggleDone(todo.id,todo.done)">

Send your ID as param when you click it.

script

methods:{
    toggleDone(id, done){
        let new_done=done==true?false —true
        let payload = {
            "id" : id,
            "done"—new_done,
        }
        axios.post("your/endpoint", payload).then(response=>{
           console.log (response.data)
        })
    }
},

PS: Don't forget to import axios

The above is the front end.This is about the backend.

routes/api

Route::post("your/endpoint", "TodoController@update");

controller

public function update(Request$request)
{

    // where done is the name of the column in the DB table.
    $payload=[
        "done" = > $request-> get("done"),
    ];

    // Todo is the name of the DB table.
    Todo::where("id", $request->get("id"))->update($payload);
    
    $todos=Todo::all()        
     
    return response()->json($todos)

}

One thing you need to be careful about here is the Model, and if you haven't decided where $fillable is, you can't update it.

Todo Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Todo extensions Model
{
    protected $guarded=[];
    protected$table="todo";
    
}

I used $guarded rather than deciding which parts I want to modify as $fillable one by one.This is faster.

Check DOCS in the label to check eloquent ORM methods such as update, create.

I'm a foreigner and I'm sorry if my Japanese is wrong.


2022-09-30 14:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.