Eloquent - Inserting variable inside selectRaw()

Viewed 54

How can you insert a variable ($TotalDistance) inside a selectRaw() using Eloquent?

public function totalPace()
{

    $TotalDistance = $this->hasMany(Runners_List::class, 'run_list_id')->sum('distance'); //60 karon
    $TotalPace = $this->hasMany(Runners_List::class, 'run_list_id')->selectRaw('SEC_TO_TIME( SUM( 
            TIME_TO_SEC( `pace` ) ) / '$TotalDistance') as total')->first();
 
     return $TotalPace;
    }

It works if I replace $TotalDistance with a number.

1 Answers

Try this:

public function totalPace()
{

    $TotalDistance = $this->hasMany(Runners_List::class, 'run_list_id')->sum('distance'); //60 karon
    $TotalPace = $this->hasMany(Runners_List::class, 'run_list_id')->selectRaw('SEC_TO_TIME( SUM( 
        TIME_TO_SEC( `pace` ) ) / ?) as total', [$TotalDistance])->first();

        return $TotalPace;
}
Related