Chapter 8. Database and Eloquent

Laravel provides a suite of tools for interacting with your application’s databases, but the most notable is Eloquent, Laravel’s ActiveRecord ORM (object-relational mapper).

Eloquent is one of Laravel’s most popular and influential features. It’s a great example of how Laravel is different from the majority of PHP frameworks; in a world of DataMapper ORMs that are powerful but complex, Eloquent stands out for its simplicity. There’s one class per table, which is responsible for retrieving, representing, and persisting data in that table.

Whether or not you choose to use Eloquent, however, you’ll still get a ton of benefit from the other database tools Laravel provides. So, before we dig into Eloquent, let’s start by covering the basics of Laravel’s database functionality: migrations, seeders, and the query builder.

Then we’ll cover Eloquent: defining your models; inserting, updating, and deleting; customizing your responses with accessors, mutators, and attribute casting; and finally relationships. There’s a lot going on here, and it’s easy to get overwhelmed, but just take it one step at a time and we’ll make it through.


Before we get into how to use Laravel’s database tools, let’s pause for a second and go over how to configure your database credentials and connections.

The configuration for database access lives in config/database.php. Like many other configuration areas in Laravel, you can define multiple “connections” and then ...

Get Laravel: Up and Running now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.