Book Image

Laravel 5 Essentials

By : Martin Bean
Book Image

Laravel 5 Essentials

By: Martin Bean

Overview of this book

Table of Contents (15 chapters)
Laravel 5 Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Retrieving data


Eloquent provides you with numerous ways to fetch records from your database, each with their own appropriate use case. You can simply fetch all records in one go; a single record based on its primary key; records based on conditions; or a paginated list of either all or filtered records.

To fetch all records, we can use the aptly-named all method:

use App\Cat;
$cats = Cat::all();

To fetch a record by its primary key, you can use the find method:

$cat = Cat::find(1);

Along with the first and all methods, there are aggregate methods. These allow you to retrieve aggregate values (rather than a record set) from your database tables:

use App\Order;

$orderCount    = Order::count();
$maximumTotal  = Order::max('amount');
$minimumTotal  = Order::min('amount');
$averageTotal  = Order::avg('amount');
$lifetimeSales = Order::sum('amount');

Filtering records

Eloquent also ships with a feature-rich query builder that allows you to build queries in code, without having to write a single line...