Laravel Ajax Call

version : Laravel 10
Post Time : 22-05-2024

Laravel Ajax Call

install laravel
        - composer create-project --prefer-dist laravel/laravel:^10.0 laravel_demo
Create AjaxDemoController Controller  :
          - php artisan make:controller AjaxDemoController
app/Http/Controllers/AjaxDemoController.php

                                      
                                        

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class AjaxDemoController extends Controller
{
   public function index(Request $request)
   {
       $id = Auth::user()->id;
       $data['user_detail'] = User::find($id);
       return view('ajax_demo',$data);
   }
   public function changeUserStatus(Request $request)
   {
       $userStatus = $request->input('userStatus');
       $id = Auth::user()->id;
       $user_detail= User::find($id);
       $user_detail->status = $userStatus;
       $user_detail->updated_at = date('Y-m-d H:i:s');
       $save_flag =  $user_detail->save();  
       if($save_flag){
           return response()->json(['status'=> true,'msg' => 'Updated Successfully.']);
       }else{
           return response()->json(['status'=> false,'msg' => 'Something Went Wrong..']);
       }
   }
}

Create ajax_demo blade file :-
Resources/views/ajax_demo.blade.php

                                      
                                        

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
       <!-- Bootstrap CSS -->
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> 
   <style>
       .error{
           color:red;
       }
       .basic-form{
           display:flex;
           justify-content:center;
       }
       .form-check .form-check-input {
           float: unset;
       }
   </style>
</head>
<body>
   <div class="mb-3 row text-center">
       <h1>USER INFO</h1>
   </div>
   <div class="row basic-form">
       <div class="col-md-6 text-center">
           <div class="form-check form-switch">
               <input class="form-check-input" type="checkbox" name="userStatus" id="userStatus" role="switch" {{ $user_detail->status == 1 ? 'checked' : ''}}>
               <label class="form-check-label" for="userStatus">User Status</label>
           </div>
       </div>
   </div>
</body>
<script>
   $(function() {
       $('#userStatus').change(function(){
           var userStatus = this.checked ? 1 : 0;
           $.ajax({
               url: "{{ route('changeUserStatus') }}",
               method: 'POST',
               dataType: 'json',
               data: {
                       "_token": "{{ csrf_token() }}",
                       userStatus: userStatus,
                   },
               success: function(response) {
                   alert(response.msg);
               },
           });
       });
   });
</script>

routes/web.php

                                      
                                        

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AjaxDemoController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
   return view('welcome');
});

Route::get('/ajax_demo', [AjaxDemoController::class,'index'])->name('ajax_demo');
Route::post('/changeUserStatus', [AjaxDemoController::class, 'changeUserStatus'])->name('changeUserStatus');