Laravel's Eloquent ORM makes data extraction easier and code more readable. Data retrievals are one of the basic needs of any web application. Laravel's Eloquent ORM makes it easy to pull data from the database.
As a first step, we need to create a model that represents the database tables. We can use the php artisan make:model
command to create models in Laravel.
php artisan make:model Product
This command creates a model class named Product. This model is located in the app/Models directory by default.
After creating a model, we can pull data from the database through this model. Eloquent ORM makes this process easy.
$products = Product::all();
The above code fetches all the data from the products
table and assigns them to the $products
variable.
During the data extraction process, we may also perform additional operations such as filtering and sorting.
$expensiveProducts = Product::where('price', '>', 100)
->orderBy('name')
->get();
The above code sorts products with prices greater than 100 by their prices and assigns them to the $expensiveProducts variable.