What is Eloquent in Laravel?
Eloquent is the ORM (Object Relational Mapper) in Laravel, it is a way that you can work with a database with simple syntax instead of writing long queries. Tables can be represented as objects, which saves the pain of working with long confusing queries.
Create a model instance Task
php artisan make:model Task
by default Task represents a single item in database table “tasks” To add shortcut for routers, we add:
use App\Task;
in the web.php
file, then we can use eloquent shortcuts like
Route::get('/tasks', function () {
// $tasks = DB::table('tasks')->get();
$tasks = Task::all();
return view('tasks.index', compact('tasks'));
});
Route::get('/tasks/{task}', function ($id) {
// $task = DB::table('tasks')->find($id);
$task = Task::find($id);
return view('tasks.show', compact('task'));
});
The commented code are the traditional way to retrieve the same information.