Using non-standard primary key with Eloquent relations (Laravel 5)

 

In my experience of using PHP web frameworks, Laravel is one of my favorites. Laravel helps faster development as well as much more simple to work with and feel very familiar if you are coming from frameworks such as Symfony.

The Eloquent ORM is one of the many things, that makes Laravel smarter. It makes simple for many developers to play with database. All these ease come with the standard pattern which recommended. If for some reason, you need a customized database design, it comes with a small cost, where you need to setup few things (Yet, it is far simple than many other frameworks do).

On one of my past works, I was having some difficulties in working with relations in Eloquent. It was because, I was using a non-standard primary key and column type.

Below is the model of my tables.

profiles-device-models
The table, ‘device_models‘ is using a primary key that is type of ‘varchar’. In standard Eloquent way of relation, it is expecting to be an ‘increment’ column type which will end up in ‘unsigned int’ in MySQL. To make this primary key compatible with Eloquent relation, you need to set additional three fields in class definitions.

  1. protected $primaryKey = ‘device_model’;
  2. public $incrementing = false;
  3. public $keyType = ‘string’;

These additional fields tell Eloquent that, the standard way of implementation is changed a bit, and please use these values instead. In addition to these properties, you need to pass the primary key field name in the function which creates the actual relation. Or else Eloquent will automatically adds _id

The complete migration and Eloquent model are presented below.

Migration for table ‘device_models’

 

Migration for table ‘profiles’

Eloquent modelĀ ‘Profile’

 

Eloquent model ‘DeviceModel’

 

Leave your comments below!!!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

Please wrap all source codes with [code][/code] tags.