img

5 min read

Running Python Code on Laravel Cloud from a Laravel Application

running python code on Laravel CloudIn one of our Laravel projects, we needed to build a system to estimate how investments could perform over a selected time period. This required handling sophisticated financial logic, ensuring accuracy, and maintaining consistency with existing calculations.

The client already had a Python-based solution that returned results. The key challenge was not rebuilding the logic from scratch, but seamlessly integrating this existing calculation engine into a modern Laravel application hosted on Laravel Cloud.

Our focus was on making this integration secure, maintainable, and transparent for developers, while ensuring the business could continue to rely on accurate, repeatable financial projections without disruption.

We evaluated three possible approaches:

  1. Rewrite the Python code in PHP

  2. Install Python and its dependencies on the server and execute the script from Laravel

  3. Bundle the Python code and its dependencies into a single executable and invoke it from Laravel, in case installing the required dependencies is not possible.

At first, rewriting the code in PHP seemed reasonable. But once we started exploring that path, the trade-offs became obvious.

Why Rewriting Python in PHP Wasn’t an Option

Python has a clear advantage when it comes to mathematically intensive and data-driven workloads. Its ecosystem is simply better suited for this type of problem.

Libraries such as:

  • SciPy → statistics, optimization, integration, signal processing

  • Pandas → time-series analysis, rolling windows, group-by operations

  • Statsmodels → econometrics, regressions, ARIMA models

  • SymPy → symbolic mathematics (derivatives, integrals)

  • NumPy → linear algebra, random number generation, Fourier transforms

are incredibly powerful, well-optimized, and battle-tested.

In practice, this meant that functionality we could implement in one day using NumPy would easily take a week or more in PHP, with more code, more edge cases, and higher maintenance costs.

So option one was off the table.

Evaluating Other Options

We then explored installing Python and its dependencies directly on Laravel Cloud during deployment. This approach made sense conceptually, but ran into practical limitations that we’ll cover shortly.

The third option, bundling Python and all dependencies into a single executable, technically worked. However, it introduced several architectural drawbacks:

  • Architecture-specific binaries (ARM vs x86 issues)

  • Larger repository size

  • Difficult debugging and maintenance

  • Poor developer experience when iterating on Python code

We kept this as Plan B, but it was far from ideal.

The Laravel Cloud Journey: Managing Python Dependencies

Python offers several dependency management tools, including:

  • venv
  • Poetry
  • uv
  • System packages via apt

We initially tried venv, but quickly hit a wall. On Laravel Cloud, you can run commands before building the Docker image, but:

  • You don’t have root access
  • You only have access to the default user
  • pip wasn’t available or installable in the usual way

Every attempt to install dependencies failed.

After trying multiple approaches and tools, we eventually landed on uv (from Astral: https://astral.sh/).

Why uv Worked

uv is a modern, fast Python package manager that allows users without root access to manage virtual environments and dependencies. This made it a perfect fit for Laravel Cloud’s constraints.

The Solution: Installing Python Dependencies via Composer & uv

Since Python was a core part of this Laravel application, we decided to integrate everything directly into composer.json.

Here’s what we added:

"post-install-cmd": [

   "bash -lc '[ -x \"$HOME/.local/bin/uv\" ] || (curl -LsSf https://astral.sh/uv/install.sh | sh)'",

   "bash -lc 'export PATH=\"$HOME/.local/bin:$PATH\"; uv venv --seed --python=python3'",

   "bash -lc 'export PATH=\"$HOME/.local/bin:$PATH\"; uv pip install -r storage/python/requirements.txt'"

],

This setup can be refactored or moved into deployment scripts, but the key benefit is simplicity:

  • uv is installed automatically

  • A Python virtual environment is created

  • All required Python dependencies are installed

As a result, running composer install is all developers need to do, both locally and in Laravel Cloud. No extra Python setup steps required.

Calling Python from Laravel

On the Laravel side, we created a small abstraction to handle Python execution.

app/Support/PythonScriptCaller.php:

class PythonScriptCaller
{
   public function runPythonCalculations(SimulationRequestData $payload): SimulationResponseData
   {
       $scriptPath = base_path('storage/python/calculator.py');


       $result = Process::timeout(2)
           ->env([
               'PYTHONUNBUFFERED' => '1',
               'PATH'             => base_path('.venv/bin'),
           ])
           ->input($payload->toJson())
           ->run("python3 $scriptPath");


       if ((int) $result->exitCode()) {
           throw new Exception($result->errorOutput());
       }


       return SimulationResponseData::from(
           array_merge(
               json_decode(
                   $result->output(),
                   true,
                   flags: JSON_THROW_ON_ERROR
               )
           )
       );


   }
}

This class:

  • Configures the virtual environment path
  • Passes JSON input to the Python script via stdin
  • Executes the script safely with a timeout
  • Returns structured JSON back to Laravel
  • Throws clear exceptions if Python fails

From a PHP developer’s perspective, this is just a normal Laravel method call. The underlying language becomes an implementation detail.

Python Script Example

Here’s a simplified Python example that receives JSON input and returns JSON output:

ef main():
   all_parameters = json.load(sys.stdin)
   final_output_json = {}


   # Your code goes here
  
   sys.stdout.write(json.dumps(final_output_json, separators=(",", ":"), ensure_ascii=False))




if __name__ == "__main__":
   main()

Final Thoughts

Laravel and its ecosystem are incredibly powerful and developer-friendly. But no single programming language is the best tool for every problem.

Some challenges are better solved with Python. Others with Go, Lua, C++, or something else entirely.

The real strength comes from knowing when to integrate, not rewrite.

This approach shows how Laravel can act as the backbone of a system while delegating specialized tasks to the languages and tools best suited for them.

img

Meet the authors

We are a 200+ people agency and provide product design, software development, and creative growth marketing services to companies ranging from fresh startups to established enterprises. Our work has earned us 100+ international awards, partnerships with Laravel, Vue, Meta, and Google, and the title of Georgia’s agency of the year in 2019 and 2021.

img
CONTACT US