Laravel Models

Introduction

In my last post (Working with databases in Laravel), I left off on a note that in my coming post I would be taking you through the steps for creating databases using the Eloquent ORM model. Since in my previous post I had you setup and configure a database connection, we are now ready to go ahead and use models to create tables for our database. The Eloquent ORM included with Laravel provides a simple ActiveRecord implementation for working with your database. Laravel has made it very simple for you to create tables because each database table has a corresponding “Model” which is used to interact with that table. By doing this, it allows to query for data in your tables, as well as insert new records into the table. Now let’s see how models are defined and used in Laravel.

Defining Models

Models are basically classes which you define to hold a table information. Models are typically located in the app/ directory, but you are free to place them anywhere that can be auto-loaded according to your composer.json file. The easiest way to create a model instance is using the make:model Artisan command:

php artisan make:model User

Eloquent Model Conventions

As stated in the previous paragraph, each model corresponds to a class which in turn holds the information for that table. Now let’s look at an example Flight model class, which we are going to use to store and retrieve information from our flights database table:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
//
}

Now let’s take a look at the different components that we have for the model we just created for the flights table:

Classes: Each class is defined according to the convention

· Located in the app/ directory.

· Namespace App must be specified right after <?php tag

· Class must extend Model class located in Illuminate\Database\Eloquent namespace

· The name of the file is the same as the class with the .php extension

Table Name: Each model class created corresponds to a table. So, the convention for the table is:

· The class is the table name in TitleCase and is singular.

· Laravel will automatically get the table name by converting class name to snake_case and making it plural unless another name is explicitly specified. So, in the above example, Eloquent will assume the Flight model stores records in the flights table. However, you can specify a custom table by using the protected $table property while creating the model. In this case, you can define it like the following:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The table associated with the model.
* @var string
*/
protected $table = 'my_flights';
}

Columns: When you create a model class, there are a number of columns that need to be specified in your model, otherwise Eloquent will set them to their default values.

· Primary Keys: As each model class you create is associated with its corresponding table, for the primary key, Eloquent will assume that each table has a primary key column named id. So, Eloquent will automatically set the primary key to the id column name, but this can be overridden with the protected $primarykey property. In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. However, if you want to set your primary key to a non-numeric value or use a non-incrementing value, then you will have to set the public $incrementing property to false.

· Timestamps: As you create your model class, Laravel expects that created_at and updated_at columns to exist in your tables. If the table does not have these columns names, the public $timestamps property must be set to false. Otherwise, Laravel will assume they exist and therefore set the property to true:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* Indicates if the model should be timestamped.
* @var bool
*/
public $timestamps = false;
}

In addition to this property, if you want to customize the format of the timestamps, you can use the $dateformat property model. This property determines how date attributes are stored in the database, as well as the format when the model is serialized to an array or JSON:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The storage format of the model’s date columns.
* @var string
*/
protected $dateFormat = ‘U’;
}

All other columns names are automatically added to the class as properties by Laravel. One last thing regarding the use of the columns timestamps is if you need to customize the name, you can set the CREATED_AT and UPDATED_AT constants in your model:

<?php
class Flight extends Model
{
const CREATED_AT = ‘creation_date’;
const UPDATED_AT = ‘last_update’;
}

Since we already know how to create a database connection, once we create a model, it will use the connection we have set. Otherwise, all eloquent models will use the default database connection configured for the application. However, Laravel gives the choice to specify different connection for the model. For that, you can use the $connection property like this:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The connection name for the model.
* @var string
*/
protected $connection = ‘connection-name’;
}

Now let’s recap the use of models to interact with databases in Laravel. As you have notice, Laravel makes it really simple to create models in form of classes that represent the physical tables stored in the database. Through these models, we will be able to interact with the database with ease. For example the following code illustrates how a model is created in Laravel:

<?php
// Class is located in App namespace
namespace App;
// Use Model class located in Illuminate\Database\Eloquent namespace
use Illuminate\Database\Eloquent\Model;
// Class extends Model
class User extends Model {
// specifies that the table does not have created_at and updated_at column names
public $timestamps = false;
// Overrides table name gotten from class name
protected $table = ‘my_users’;
// Columns with date/time data type
protected $dates = [‘created’, ‘last_received’];
}

As you see the code for creating is very simple and you only need to set the values for the properties you are using for your model. All of the other properties will be handled automatically by Eloquent and it will set them to the default value. Also each model starts with the <?php tag to indicate this is a php file and will be saved as the class name with the extension .php.

Conclusion

Although the contents for working with databases using Eloquent models has not been fully covered in this blog I would recommend you go to this link to learn more about this powerful query builder which allows you to fluently query your database table associated with the model you just created: Here is the link for more information on Eloquent ORM models: https://laravel.com/docs/5.4/eloquent#retrieving-models. Furthermore, as we move on to the next blog in this series, I will be talking about Database Migrations which follows up this blog since it is through this module you will create the tables associated with the models classes created during this entry. So, I hope you are fired up to learn about the next entry Database Migrations. Don’t go away the next one will be posted soon.