🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel Eloquent Models

Eloquent is Laravel's tool for working with database rows as objects. A model is a class that stands for one table.

Read every row

This line reads all three tasks as Task objects.

return Task::orderBy('title')->pluck('title')->implode(', ');

Filter first

This line finds the first unfinished task. Eloquent works with database rows as objects.

return Task::where('done', false)->orderBy('title')->first()->title;

Count the rows

This line counts every task in the table.

return (string) Task::count();

Find one row

This line finds the task called Call Ana.

return Task::where('title', 'Call Ana')->first()->title;

Example

Route::get('/tasks', function () {
    return Task::orderBy('title')
        ->pluck('title')->implode(', ');
});

Key points

  • Eloquent: the part of Laravel that maps tables to classes.
  • Model: a class that stands for one table.
  • Use Task::all() to read every row as a Task.
  • Use Task::where() to filter rows before reading them.
  • Use Task::count() to count the rows in a table.

In this example, the route answers at /tasks. The Task model stands for the tasks table. The orderBy call sorts the rows by title. The pluck call takes only the titles. The joined titles are Buy milk, Call Ana, and Write report.

Note

Each Task holds one row, so its fields are plain values.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What is a model in Laravel?