How to check data inserted or deleted in pivot after toggle method

Updated at 31-Jul-2021, By samar

How to check data inserted or deleted in pivot after toggle method

We will use programming in this lesson to attempt to solve the "How to check data inserted or deleted in pivot after toggle method".

You can easily check if data is inserted or deleted in the pivot table after the toggle method. Basically, toggle method insert data in pivot table if record with same (provided) data do not exist in it else it deletes the record from the pivot table.
  • Return json response after toggle method on pivot table

    $user = User::find($userId);
    $roleId = $request->id;
    $response = $user->roles()->toggle($roleId);
    return response()->json(['success'=>$response]);
    

    The toggle method returns an object if the new record is created in the pivot table, else it returns 1 as a response after the toggle method deletes the existing record. Basically, the toggle method deletes the record if the record already exists in it, else insert the new record.

  • JQuery check the object is empty or not in HTML page on ajax call

    //Anchor tag to get the role id on click it
    <a href="javascript:void(0)" class="add-role" data-id="1">  Role  </a>
    
    //Call ajax on click anchor tag
    $('.add-role').click(function(){    
        var id = $(this).data('id');
        $.ajax({
            type:'POST',
            url:'/ajax-role',
            data:{id:id},
            success:function(data){
                if($.isEmptyObject(data.success.attached)){
                    console.log('Record is deleted from pivot table');
                }else{
                    console.log('Record is created in pivot table');
                }
            }
        });
    });
    

    You can easily check that the object is empty or not in HTML using the jquery method $.isEmptyObject(). It will return true if the data is an empty object.

Back to code snippet queries related laravel