How to Create And Define Eloquent Model in Laravel?

Eloquent is a very interesting concept in Laravel. It is Laravel’s flagship database tool out of the box which is built using Laravel Query builder. It is easy to understand and use for any developer. Basically Eloquent is an “ActiveRecord” ORM, which means it is a single abstraction layer to deal with multiple types of databases. It means Eloquent doesn’t case which type of databases you are using or how many are there. It’s implementation is simple and consistent with all of them. Here is how we can create and define Laravel eloquent against any table. First we need to create a model, lets say Contact model by running this command.

php artisan make:model Contact

Now our Contact model will look like this.

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{

}

Here you should note that we are using Illuminate\Database\Eloquent\Model class. This class holds the key to all the operations and methods. This class has all the methods which we will call later like create, save, delete, where and many more. For example, by default this Contact models will be attached to contacts table but we can attach it to some other table by using this line in Contact class.

protected $table = 'contacts_dev';

we can tell which columns of contacts table should be exposed to users input by insertion or mass insertions using create() or make() method.

protected $fillable = ['name', 'email', 'phone_number'];

We can also tell Laravel eloquent to protect these columns from users input on mass assignment.

protected $hidden = ['id', 'created_at', 'updated_at'];

Laravel eloquent will auto-increment IDs when we will add records but we can change this behaviour by using this line in Contact class.

protected $incrementing = false;

Eloquent expects to have created_at and updated_at in every table but you can also disable this functionality using this line.

protected $timestamps = false;

We can also set date formate by using this line. By default, eloquent will use date() method of php.

protected $dateFormat = 'U';

We can set connection to any other database if we are dealing with multiple databases.

protected $connection = 'sql_dev';

By default Eloquent takes ‘id’ as primary key in any table but we can define some other column as primary key by using this line.

protected $primaryKey = 'contact_id';

We can use $casts to cast any attribute to native type.

protected $casts = [
		'email_verified_at' => 'datetime',
	];

If you have any questions please leave a comment. We really appreciate that.