Search code examples
phpajaxlaravelliveinsert-update

Error. How can i make live table update and delete using ajax in laravel


i try to make editable role in user table but its error and not update data to database

here the error

enter image description here

this is my blade

<div class="table-responsive">
        @csrf
        <table id="editable" class="table table-bordered table-striped">
          <thead>
            <tr>
              <th>ID</th>
              <th>First Name</th>
              <th>Email</th>
              <th>Role</th>
            </tr>
          </thead>
          <tbody>
            @foreach($allusers as $row)
            <tr>
              <td>{{ $row->id }}</td>
              <td>{{ $row->name }}</td>
              <td>{{ $row->email }}</td>
              <td>{{ $row->role }}</td>
            </tr>
            @endforeach
          </tbody>
        </table>
      </div>

and here my controller route

Route::post('tabledit/action', 'App\Http\Controllers\EventController@action')->name('tabledit.action');

and here my function inside EventController

function action(Request $request)
{
    if($request->ajax())
    {
        if($request->action == 'edit')
        {
      $data = $request->role;
      $updaterole = DB::table('users')
                ->where('id', $request->id)
        ->first();

        $updaterole = $data;
        $update->update();

        }

        if($request->action == 'delete')
        {
            DB::table('users')
                ->where('id', $request->id)
                ->delete();
        }
        return response()->json($request);
    }
}

and here my view enter image description here

can someone pls help me


Solution

  • It's better to use if request has instead of request action.

    if($request->has('edit')
    {
    //
    }
    

    But i didn't change it. Only edited update section.

    function action(Request $request)
        {
            if($request->ajax())
            {
                if($request->action == 'edit')
                {
              $data = $request->role;
              DB::table('users')->where('id', $request->id)->update(['role' => $data]);
                }
        
                if($request->action == 'delete')
                {
                    DB::table('users')->where('id', $request->id)->delete();
                }
                return response()->json($request);
            }
        }