You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中使用jQuery每分钟检测数据库指定行是否存在

Implementing Periodic Droplets Table Check with jQuery in Laravel Blade

Let's walk through how to build this feature where your Blade view checks the Droplets table every minute for a row matching a specific webshop->id, and updates a progress bar when found.

1. Set Up the Progress Bar in Your Blade View

First, add the HTML for your progress bar (I'll use Bootstrap's progress component as an example—adjust based on your styling):

<div class="progress mt-3" style="display: none;">
  <div class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<p id="status-message" class="mt-2">Waiting for Droplet to be created...</p>

We start with the progress bar hidden, since we only want to show it once the matching row is found.

2. Write the jQuery Script for Periodic Checks

Add this script at the bottom of your Blade view (or in a separate JS file included in the view):

$(document).ready(function() {
    // Get the specific webshop ID from your Blade template
    const webshopId = {{ $webshop->id }};
    let checkInterval;

    // Function to check the Droplets table
    function checkDropletExists() {
        $.ajax({
            url: '/check-droplet-status',
            method: 'GET',
            data: { webshop_id: webshopId },
            success: function(response) {
                if (response.exists) {
                    // Stop the interval once we find the row
                    clearInterval(checkInterval);
                    
                    // Show the progress bar and update its status
                    $('.progress').show();
                    $('#status-message').text('Droplet found! Starting setup...');
                    
                    // Example: Simulate progress bar update (replace with actual progress logic if needed)
                    let progress = 0;
                    const progressInterval = setInterval(() => {
                        progress += 10;
                        $('.progress-bar').css('width', `${progress}%`).attr('aria-valuenow', progress);
                        if (progress >= 100) {
                            clearInterval(progressInterval);
                            $('#status-message').text('Setup complete!');
                        }
                    }, 500);
                }
            },
            error: function(xhr) {
                console.error('Error checking droplet status:', xhr.responseText);
            }
        });
    }

    // Start checking every 60 seconds (1 minute)
    checkInterval = setInterval(checkDropletExists, 60000);
    
    // Optional: Run the check immediately on page load
    checkDropletExists();
});
  • We use setInterval to trigger the check every 60,000 milliseconds (1 minute).
  • Once the matching row is found, we clear the interval to stop further checks, then show and animate the progress bar.
  • The webshopId is passed directly from your Blade template using Laravel's echo syntax.

3. Create the Backend Route and Controller Method

You need a backend endpoint to handle the database check.

First, add a route in routes/web.php (or routes/api.php if using API routes):

// Web route example (include CSRF token in AJAX if using this)
Route::get('/check-droplet-status', [DropletController::class, 'checkStatus']);

Then, in your DropletController.php, add the checkStatus method:

use App\Models\Droplet;
use Illuminate\Http\Request;

public function checkStatus(Request $request) {
    // Validate the incoming webshop ID
    $request->validate([
        'webshop_id' => 'required|integer|exists:webshops,id'
    ]);

    // Check if a Droplet exists with the given webshop ID
    $exists = Droplet::where('webshop_id', $request->webshop_id)->exists();

    return response()->json(['exists' => $exists]);
}
  • We validate the webshop_id to ensure it's valid and exists in your webshops table.
  • The method checks the Droplets table for a matching row and returns a JSON response with exists: true/false.

4. Important Notes

  • CSRF Protection: If you're using web routes (not API routes), make sure your AJAX request includes the CSRF token. You can add this to your Blade view:
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    And add this to your jQuery script before the AJAX call:
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
  • Resource Cleanup: Always clear intervals when the page is unloaded to prevent unnecessary requests. Add this to your script:
    $(window).on('beforeunload', function() {
        clearInterval(checkInterval);
    });
    
  • Progress Logic: The progress bar animation in the example is a simulation. Replace it with actual progress tracking (e.g., checking a progress column in the Droplets table) if your setup requires real progress updates.

内容的提问来源于stack exchange,提问作者user5838715

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:06:44