How to use percentage in a laravel query?

by raven_corwin , in category: PHP Frameworks , 21 days ago

How to use percentage in a laravel query?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 20 days ago

@raven_corwin 

You can use percentages in a Laravel query by using the DB facade to execute a raw SQL query. Here's an example of how you can use a percentage in a Laravel Eloquent query:

1
2
3
4
5
6
7
8
use IlluminateSupportFacadesDB;

$percentage = 50;

$users = DB::table('users')
            ->select('*')
            ->where('age', '>', DB::raw('(SELECT AVG(age) FROM users) * ' . $percentage / 100))
            ->get();


In the above example, we are selecting all users whose age is greater than 50% of the average age of all users in the database.


You can adjust the percentage value as needed for your query. Keep in mind that using raw SQL queries directly in your application can be potentially unsafe, so make sure to sanitize user input and use proper validation to prevent SQL injection attacks.