How to update user status using toggle button in laravel?

File name : UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
public function index()
{
$users = User::get();
return view('users',compact('users'));
}

public function changeStatus(Request $request)
{
$user = User::find($request->user_id);
$user->status = $request->status;
$user->save();

return response()->json(['success'=>'Status change successfully.']);
}
}

View

File name : users.blade.php

<!DOCTYPE html>
<html>
<head>
<title>how to update user status using toggle button</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" ></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
</head>
<body>
<div class="container">
<h1>how to update user status using toggle button</h1>
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Status</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
<input data-id="{{$user->id}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $user->status ? 'checked' : '' }}>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</body>
<script>
$(function() {
$('.toggle-class').change(function() {
var status = $(this).prop('checked') == true ? 1 : 0;
var user_id = $(this).data('id');

$.ajax({
type: "GET",
dataType: "json",
url: '/changeStatus',
data: {'status': status, 'user_id': user_id},
success: function(data){
console.log(data.success)
}
});
})
})
</script>
</html>

File name : web.php

Route::get('users', 'UserController@index'); Route::get('changeStatus', 'UserController@changeStatus');





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here


Ittutorial