Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Raw Queries as a Last Resort

Premium
1:50

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 of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…