Skip to content
Advertisement

How can I round off all the rating, but ignore it if it is null or empty in laravel?

How can I round off all rating but ignore it if its null or 0?

Below is my code:

$star = $ratings->count() > 0 ? 
    round($ratings->sum('rating') / $ratings->count(), 2) :
    'No rating yet';

Advertisement

Answer

You can achieve this using the following code

$star = $ratings->count() > 0 ? (empty($ratings->sum('rating'))?$ratings->sum('rating'): round($ratings->sum('rating') / $ratings->count(), 2)) : 'No rating yet';

I would recommend if you go this checking in Eloquent Using below code

$model = Model::avg('rating'); 
$star = is_null($model->rating)?'No rating yet': round($model->rating,2);

The above will be memory-optimized. As the way you were doing it will bring all the records from the Database and Load in the memory. If you only want to show average getting only Average from the Database is more memory optimized and will improve performance later on

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement