Skip to main content

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? (30 h 50 min)

You also get:

55 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…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.