Laravel Ajax Button

by John H
2 minutes

in blade

<button class="btn-xs btn-info grant_access" data-options='{"user_id":"{{ $user->id }}", "action": "remove", "role_id" : {{ $role_id }}, "_token": "{{ Session::token() }}" }'>Has Access<h;/button>

<script>
$('.grant_access').click(function(){
    var options = $(this).data( "options");
    var sel = $(this);

    //console.log(options);
    $.ajax({
        method: 'post',
        url: '/pat-admin-access',
        data: options,
        dataType: 'JSON',
    }).done( function( response ) {
        //console.log(response);
        if (response['result']) {
            sel.addClass((response['action'] == 'grant')?  'btn-info' : 'btn-warning');
            sel.removeClass((response['action'] == 'grant')? 'btn-warning' : 'btn-info');

            sel.text((response['action'] == 'grant')  ? "Has Access" : "Grant Access");
            sel.data('options').action = (response['action'] == 'grant') ? 'remove' : 'grant';
        } else {
            sel.text('There was problem');
        }

    });

});                         
</script>

in route

Route::post('/pat-admin-access/', [
   'middleware' => 'AppControl:pat-admin-access',
    'redirect' => 'request_access',
    'uses' => 'PatController@updateUserForAdminControl'
])
->name('pat-admin-access')
;

in controller

public function updateUserForAdminControl(Request $request) {
        // $data = $request->only('action', 'user_id', 'role_id');
        $data = $request->all();
        if ($data['action'] == 'grant') {
            \DB::table('role_users')->insert([
                'user_id' => $data['user_id'],
                'role_id' => $data['role_id']
            ]);
        } else if ($data['action'] == 'remove') {
            \DB::table('role_users')
                ->where('user_id', '=', $data['user_id'])
                ->where('role_id', '=', $data['role_id'])
                ->delete();
        }

        return $response = ['action'=>$data['action'], 'msg'=>'success', 'result' => true];

    }

Related Articles

Laravel Save Form Post

php artisan make:migration tasks in database / migrations / create tasks table - paste in up() ...

John H John H
~1 minute

Make a Form Cancel Button

  The Cancel Button You are making an edit form for a site. The form allows a users to make...

John H John H
9 minutes

Laravel Deployment on Ec2

You gotta have composer installed cd /home/ec2-user/ sudo curl -sS...

John H John H
2 minutes