SQL Queries in laravel with Heredoc: A Clean and Readable Approach

Sandeeppant
2 min read5 days ago

--

While raw SQL queries can be powerful for complex operations, they often become hard to read and maintain, especially as the application grows. A great way to achieve this is by using Heredoc syntax. This allows us to write multi-line SQL queries in more structured and readable format without worrying about concatenation or escaping issues.

What is Heredoc?

Heredoc is a PHP syntax feature that enables writing multi-line strings without needing to escape characters or use concatenation operators. It starts with ‘<<<' followed by an identifier (usually SQL), and it ends with the same identifier on a new line.

Why Use Heredoc in Laravel SQL Queries?

  1. To improve the readability of complex raw queries.
  2. To avoid concatenation
  3. To write raw sql queries cleanly

Here are some Examples that may help you to understand the way of using heredoc syntax in laravel queries:

$sql = <<<SQL
SELECT users.id, users.name, COUNT(orders.id) as total_orders
FROM users
LEFT JOIN orders ON users.id = orders.user_id
WHERE users.status = 'active'
GROUP BY users.id
ORDER BY total_orders DESC
SQL;

$results = DB::select($sql);

Laravel provides query bindings to prevent SQL injection. Heredoc can still be used effectively with prepared statements:

$sql = <<<SQL
SELECT * FROM users WHERE id = ?
SQL;

$results = DB::select($sql, 1);

If you’re defining complex database structures, Heredoc can help when executing raw SQL statements inside migrations.

Schema::create('logs', function (Blueprint $table) {
$table->id();
$table->string('event_type');
$table->timestamps();
});

DB::statement(<<<SQL
CREATE TRIGGER after_insert_logs
AFTER INSERT ON logs
FOR EACH ROW
BEGIN
INSERT INTO log_audit (log_id, action, created_at)
VALUES (NEW.id, 'insert', NOW());
END;
SQL);

Using Heredoc for SQL queries in Laravel can significantly improve the clarity of your raw SQL code. If you work with complex SQL logic in Laravel, give Heredoc a try!

Have you used Heredoc in Laravel before? Share your experiences in the comments! 🚀

#laravel #php #eloquent #sql

--

--

No responses yet