How can we use the new Laravel Eloquent ORM?

The Eloquent ORM is included with Laravel framework and provides a beautiful, simple ActiveRecord implementation to work with your database. Each database table has a corresponding “Model” which we use to interact with that table.

To use Laravel Eloquent, we first create an Eloquent model.

Create an Eloquent Model

Models are mostly located in the app directory, but you can place them anywhere and auto-load according to your composer.json file. All Eloquent models extend Illuminate\Database\Eloquent\Model. You can make a new Model using the command below.

php artisan make:model Customer

Here we did not tell Eloquent which table to use for our Customer model. The plural name of the class will automatically be used as the table name unless we explicitly specify another name. So, here, Eloquent assumes the Customer model stores records in the customers table. You can specify a custom table by defining a table property on your model.

class Customer extends Model {
    protected $table = 'my_customers';

Eloquent assures that each table has a primary key column as id. If you define the primaryKey property, it overrides the convention. Similarly, you can also define a connection property that overrides the database name connection we will be using in the model.

Once we define a model, we can retrieve data and create new records for a table. You should add updated_at and created_at columns to your table by default. Otherwise, set the $timestamps property on your model to false.

We can use the Eloquent Models to perform various operations on our database connections and table.

Laravel Eloquent Use Cases

To retrieve all records using a Model. This helps retrieve all data of a customer. The model class can be used in a Controller to portray or manipulate customer data.

$customers= Customer::all();

To retrieve a record by primary key. This helps finding a specific customer’s information with use id 1 or any other specified id number.

$customer = Customer::find(1);

To retrieve a model by primary key or throw an exception.

$model = Customer::findOrFail(1);
$model = Customer::where('votes', '>', 200)->firstOrFail();

Querying using Eloquent Models. We can create queries as in SQL and retrieve information from database. The results can directly be submitted to Controller class.

$customers = Customer::where('votes', '>', 200)->take(10)->get();
foreach ($customers as $customer)

Aggregate functions using Eloquent. Laravel Eloquent supports use of aggregate functions like count, get and sum as shown below.

$count = Customer::where('votes', '>', 200)->count();
$customers = Customer::whereRaw('age > ? and votes = 200', [25])->get();

Specify Query Connection. We can also find data for a specific database connection, in case we have multiple databases in our application.

$customer = Customer::on('connection-name')->find(1);