🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel Query Builder

The query builder builds database queries in PHP code. A query asks the database for chosen rows.

Read a table

This line reads every row from the tasks table, sorted by title.

return DB::table('tasks')->orderBy('title')
    ->pluck('title')->implode(', ');

Keep matching rows

This query keeps only unfinished tasks. The query builder builds database queries in PHP code.

return DB::table('tasks')->where('done', false)
    ->pluck('title')->implode(', ');

Take the first row

This line takes the first unfinished task by title.

return DB::table('tasks')->where('done', false)
    ->orderBy('title')->first()->title;

Count the rows

This line counts the unfinished tasks.

return (string) DB::table('tasks')
    ->where('done', false)->count();

Example

Route::get('/open-tasks', function () {
    return DB::table('tasks')->where('done', false)
        ->orderBy('title')->pluck('title')->implode(', ');
});

Key points

  • Query builder: the DB class that builds queries without raw SQL.
  • Use DB::table('tasks') to start a query on the tasks table.
  • Use where() to keep only rows that match a rule.
  • Use orderBy() to sort the rows.
  • Use first() to take the first matching row.

In this example, the route answers at /open-tasks. The query starts on the tasks table. The where call keeps only unfinished tasks. The orderBy call sorts them by title. The pluck call takes only the titles. The joined titles are Buy milk and Call Ana.

Note

The builder returns plain rows, not objects.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does where('done', false) do?