Courses

Laravel 11 Eloquent: Expert Level

Raw Queries as a Last Resort

Summary of this lesson:
- Implementing raw SQL queries in Laravel
- Using selectRaw() and whereRaw()
- Understanding raw query parameters
- Best practices and security considerations

Let's finish this course chapter about querying the data from Eloquent by reminding you that there are also raw queries.

If you have some function in your database engine like MySQL, but it's not present in Eloquent, you need specifically the functions from MySQL. Of course, you can use that in raw queries.


For example, I have ten task records in the database and want to show only one month from the created_at field.

In the select, you can use DB::raw(); inside this method, use SQL functions.

use App\Models\Task;
use Illuminate\Support\Facades\DB;
 
$tasks = Task::select(DB::raw('id, description, MONTH(created_at) as created_month)'))->get();
 
foreach ($tasks as $task) {
dump($task->id . ': ' . $task->description . ' - month ' . $task->created_month);
}

Or, instead of using DB::raw(), you can use...

The full lesson is only for Premium Members.
Want to access all 28 lessons of this course? (71 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord