Laravel Reading Records
Reading a record fetches a stored row from a table. Eloquent returns the row as a Task.
Read every row
This line reads all three tasks, sorted by title.
return Task::orderBy('title')->pluck('title')->implode(', ');Read the first row
This line reads the first task by title. Reading a record fetches a stored row from a table.
return Task::orderBy('title')->first()->title;Read one named row
This line reads the task called Call Ana.
return Task::where('title', 'Call Ana')->first()->title;Read finished rows
This line reads only the finished tasks.
return Task::where('done', true)->pluck('title')->implode(', ');Example
Route::get('/tasks/open', function () {
return Task::where('done', false)
->orderBy('title')->pluck('title')->implode(', ');
});Key points
- Read: to fetch a stored row from a table.
- Use Task::all() to read every row.
- Use first() to read the first matching row.
- Use where() before first() to narrow the search.
In this example, the route answers at /tasks/open. 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
first() gives null when no row matches.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which call reads the first matching row?