Integrating YOLO Predictions into a Laravel Project
Incorporating YOLO (You Only Look Once) into a Laravel project can be a powerful way to handle object detection tasks such as image analysis, counting, and classification. YOLO, a state-of-the-art object detection algorithm, works seamlessly with Python, and integrating it into a PHP-based framework like Laravel requires bridging the gap between the two languages.
This article will guide you through setting up YOLO predictions in a Laravel project, complete with code examples. We’ll build a simple system where users upload an image, YOLO processes the image to detect objects, and Laravel displays the predictions.
Contact me if you need help https://x.com/microDesignn
Prerequisites
- YOLO Model Setup: Ensure you have a YOLOv5/YOLOv8/YOLOv11 model trained and ready for inference.
- Laravel Environment: Laravel 11 installed and configured.
- 
Python Environment: Python installed with dependencies for YOLO (e.g., ultralyticsfor YOLOv8).
- Server Setup: Ensure the server can execute Python scripts using Laravel's PHP.
Workflow Overview
- User uploads an image through Laravel.
- Laravel processes the request and sends the image to a Python YOLO script.
- YOLO predicts the objects and returns the results to Laravel.
- Laravel displays the predictions.
Step 1: Setting Up Laravel
Install Laravel Project
Start by creating a new Laravel project or using an existing one:
composer create-project laravel/laravel yolo-integration
Set up your environment variables in .env for database and file storage:
APP_NAME="YOLO Integration"
APP_ENV=local
APP_KEY=base64:...
APP_DEBUG=true
APP_URL=http://localhost
FILESYSTEM_DISK=public
Create Routes and Controller
Define routes in routes/web.php:
use App\Http\Controllers\YOLOController;
Route::get('/', [YOLOController::class, 'index'])->name('home');
Route::post('/predict', [YOLOController::class, 'predict'])->name('predict');
Create a YOLOController:
php artisan make:controller YOLOController
YOLOController Implementation
Edit YOLOController.php:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class YOLOController extends Controller
{
    public function index()
    {
        return view('upload'); // Show the upload form
    }
    public function predict(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);
        // Store the uploaded image
        $imagePath = $request->file('image')->store('uploads', 'public');
        // Execute Python script
        $pythonScript = base_path('scripts/yolo_predict.py');
        $imageFullPath = storage_path('app/public/' . $imagePath);
        $command = escapeshellcmd("python3 $pythonScript $imageFullPath");
        $output = shell_exec($command);
        if (!$output) {
            return back()->with('error', 'Error processing image.');
        }
        // Decode the JSON response from the Python script
        $predictions = json_decode($output, true);
        return view('results', compact('predictions', 'imagePath'));
    }
}
Create Views
- Upload Form (resources/views/upload.blade.php):
<!DOCTYPE html>
<html>
<head>
    <title>YOLO Object Detection</title>
</head>
<body>
    <h1>Upload an Image for YOLO Prediction</h1>
    @if(session('error'))
        <p style="color: red;">{{ session('error') }}</p>
    @endif
    <form action="{{ route('predict') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <input type="file" name="image" required>
        <button type="submit">Upload and Predict</button>
    </form>
</body>
</html>
- Results Page (resources/views/results.blade.php):
<!DOCTYPE html>
<html>
<head>
    <title>YOLO Prediction Results</title>
</head>
<body>
    <h1>Prediction Results</h1>
    <img src="{{ asset('storage/' . $imagePath) }}" alt="Uploaded Image" width="400">
    <ul>
        @foreach($predictions as $prediction)
            <li>{{ $prediction['label'] }}: {{ $prediction['confidence'] * 100 }}%</li>
        @endforeach
    </ul>
    <a href="{{ route('home') }}">Upload Another Image</a>
</body>
</html>
Step 2: Setting Up YOLO Python Script
Create a Python script scripts/yolo_predict.py in your Laravel project root:
import sys
import json
from ultralytics import YOLO
def main(image_path):
    # Load YOLO model
    model = YOLO("yolov8n.pt")  # Use the appropriate model
    # Perform prediction
    results = model(image_path)
    # Parse results
    predictions = []
    for box in results[0].boxes:
        predictions.append({
            "label": box.cls,
            "confidence": box.conf.item()
        })
    # Output predictions as JSON
    print(json.dumps(predictions))
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python yolo_predict.py <image_path>")
        sys.exit(1)
    image_path = sys.argv[1]
    main(image_path)
Install YOLO dependencies:
pip install ultralytics
Step 3: Test the System
- Start Laravel:
php artisan serve
- Upload an image via the form.
- View the prediction results.
Additional Notes
- Security: Ensure Python scripts are sanitized and cannot execute arbitrary commands.
- Performance: If prediction times are high, consider running YOLO in a dedicated Python server (e.g., Flask API).
- Model Customization: Train YOLO on your dataset to improve prediction accuracy for domain-specific tasks.
This setup provides a robust framework to integrate YOLO predictions into a Laravel project, enabling real-time image analysis for web applications.
 
 
              
 
    
Top comments (0)