John Davidson

php - Laravel query on which is more performant


I am fairly new to laravel and sql I noticed that a lot of things can be achieved using different techniques. I want to know which is more performant?

Message::where('user_id', auth()->user()->id)->get()



Someone I know warned me about eager loading that it greatly affects performance.

My Answer:

This query uses the Eloquent ORM to retrieve all messages where the user_id column matches the currently authenticated user's id. Eloquent is a powerful and convenient way to interact with your database in Laravel, but it can sometimes be less performant than writing raw SQL queries.

To compare the performance of this query with a raw SQL query, you can use the DB facade in Laravel to execute the same query using raw SQL:

DB::select('SELECT * FROM messages WHERE user_id = ?', [auth()->id()]);

In general, raw SQL queries can be more performant than Eloquent queries because they allow you to write optimized queries tailored to your specific needs. However, Eloquent provides a more convenient and expressive way to interact with your database, especially for simple queries like the one above.

If performance is a concern for your application, you may want to consider using raw SQL queries for complex or performance-critical queries, while still taking advantage of Eloquent for simpler queries or when convenience is more important than performance.

Rate this post

3 of 5 based on 1823 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us