Home > Mobile >  How do I update data in laravel?
How do I update data in laravel?

Time:11-12

I am trying to update my already existing user. But I really do not know how to do it.

this is the API route that I am using to update the user

Route::put('/user/{user}', [UserController::class, 'updateUser']);

The function in the usercontroller is this:

public function updateUser(Request $request, User $user){
        $data = $request->validate([
            'username' => '',
            'firstname' => '',
            'lastname' => '',
            'email' => '',
            'password' => '',
            'phone_number' => '',
            'role' => '',
            'companyID' => '',
            'companyRole' => '',
        ]);

        $input = $request->all();
        $user->update($input);
        return $user;
    }

This is the function that I use in vue to send the new user data to laravel:

editUser(){
            console.log(this.user)
            this.$axios
                .put('api/user/'   this.$route.params.id   this.user)
                .then((response) => {
                    console.log(response.data)
                })
                .catch((err) => {
                    console.log(err)
                })
        }

This is the "this.user"

{ "id": 1, "username": "user", "firstname": "user", "lastname": "user", "email": "[email protected]", "email_verified_at": null, "phone_number": 6282223, "role": "user", "companyID": 2, "companyRole": "employee", "logged_in": 0, "created_at": "2021-11-11T12:00:23.000000Z", "updated_at": "2021-11-11T12:00:23.000000Z" }

And the "this.$route.params.id" is just the user id

I do not know what I am doing wrong. It is not updating

CodePudding user response:

Laravel param binding can give you the user by only passing the id.

The main error here is how you are calling your API.

Change axios from this:

this.$axios.put('api/user/'   this.$route.params.id   this.user)

To this:

this.$axios.put(`api/user/${this.$route.params.id}`, this.user)

This way laravel will recive the ID and convert it to the user, also recive the payload sended in "this.user".

CodePudding user response:

Maybe I would try another approach in order to update a user with specific id.

In web.php file where you define your Routes put:

Route::get('/update_user', '\App\Http\Controllers\PostController@update_user');

In your Controller in my example PostController:

public function update_user()
{
   //Find all users 
   $users = DB::select('select * from users');

   foreach($users as $user){
       //UPDATE
       DB::update('update users set email = "[email protected]" where id = ?',[4]);
   }

   //If you want echo an alert message for the result
   echo '<script>alert("The email of user with id = 4 has been updated.")</script>';

}

Try to shape the code for your needs, but the basic idea is the above.

  • Related