Skip to content
Advertisement

Laravel – Star rating – Optimization?

It’s not a problem in fact, but I would like to know if it is possible to optimise the code below.

It’s a simple code to show the star rating mark which is in the db.

I searched and tried with @foreach, but can’t figure it out.

Code:

JavaScript

When $review->rate <= 0 enter image description here

When $review->rate === 3 enter image description here

When $review->rate >= 5 enter image description here

Advertisement

Answer

Don’t Repeat Yourself. Loop 5 times and write a condition to check if the star should be empty.

Code: (Demo: https://3v4l.org/Tj31J )

JavaScript

Output:

JavaScript

I don’t code in Laravel, correct me if this syntax is flawed:

JavaScript

If you want to incorporate half-empty (aka half-full) stars, just add another condition. The same design logic applies, add one more condition to check if the star should be halved. Here is a full battery of valid ratings tested:

Code (See the Demo for verbose output: https://3v4l.org/r4c6R )

JavaScript

If you don’t understand the inline conditional syntax, google is only a click away.

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