What is meant by whereRaw in PHP Laravel framework
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
Imagine yourself on a treasure hunt, the ground is filled with different clues and hints, some of which are in plain sight while others can be decoded. In the world of programming, databases offer a similar experience, and Laravel's whereRaw plays a significant role in unlocking hidden information. Let's explore this concept together.
What is whereRaw?
whereRaw helps developers access the raw query builder of Laravel to perform custom database queries without relying on Eloquent models or the standard query builder. It provides the flexibility to write complex, low-level SQL queries for efficient and finely controlled queries.
How does whereRaw work?
When you want to execute a complex query that cannot be expressed using Eloquent model methods or standard query builder functions, Laravel comes in handy with its raw database access through the whereRaw method. It takes in a string containing valid SQL statements and executes them directly against your database connection without altering the original structure.
Best Practices for using whereRaw
- Always use parameter binding to prevent SQL injection attacks.
- Test your queries before implementing them in production systems and applications.
- Sanitize the input data used in the query.
- Write efficient queries that are optimized for performance and speed.
Example: Fetching Usernames with whereRaw
$userNames = DB::table('users')->select('username')->whereRaw("`username` like CONCAT(?, '%')", ["John"])->get()->pluck('username');
echo $userNames;
Conclusion
The whereRaw method in Laravel offers developers the power to write complex SQL queries and gain precise control over database interactions. However, it's essential to use best practices and follow security measures to ensure your querying is safe from attacks. With these insights, you can now confidently add whereRaw to your Laravel development toolkit for better performance and flexibility.