Fayakon
Fayakon

Reputation: 1523

Laravel: Ajax update to database

i just want to update my data via ajax i am getting error. Error Console:

POST http://abc.local/teachers/users/1 404 (Not Found)

here is my controller:

public function policyupdate(Request $request, $id)
              {

         $user = DB::table('users')->find($id);
        $user->update($request->all());
          return response()->json([
            'status' => 'success',
            'msg' => 'has been updated'
        ]);
         }

web.php:

Route::post('users/{user}','TeachersController@policyupdate') ;

js:

jQuery(document).ready(function(e)  {
  alert(1);
$('#update-policy').on('click', function(e) {
console.log('Update policy clicked!')
    e.preventDefault(e);

        $.ajax({
 type: "POST",
            url: "users/" + $('#update-policy').attr("value"),
        data:  $(this).serialize(),
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },

            success: function (data) {
          alert(updated);
              },

        });
    });
});

Upvotes: 1

Views: 140

Answers (1)

porloscerros Ψ
porloscerros Ψ

Reputation: 5078

I only notice a couple of issues.

url: "users/" + $('#update-policy').attr("value"),

In the url of the ajax call you don't have a slash at the beginning, so the url will be relative to the url of the page where the function is located, instead of the base url. to solve it just add that slash at the beginning

url: "/users/" + $('#update-policy').attr("value"),

The other one is that you have an input with the put method,

<input type="hidden" name="_method" value="put" />

so the Laravel route should be put (it makes sense if it takes into account that it is a route to update)

Route::put('users/{user}','TeachersController@policyupdate') ;

Well, and as you yourself discovered, with query builder, the update() method works if you query with where() instead of find()

$user = DB::table('users')->where('id', $id)->update( $request->all() );

Upvotes: 2

Related Questions