Jurin Liyun
2 min readDec 2, 2018

--

The Beginner Guide to Laravel ORM: The Legacy perspective (Part 1)

I have been asked by my colleague about how to use laravel ORM when it comes to not following the convention. This happen mostly when we have an existing database. Actually there’s no magic to understand how laravel ORM being implemented in this kind of problem.

I think, I will not go into Laravel ORM in depth in this article, but I will try to expose the key to understand it. Though one can read it through Laravel documentation, but for beginner, reading standard documentation making it hard for them to understand. In this article i will pick the most common ORM terms as follows:

If you need more details on this you can go directly to its official documentation. Lets get started

  1. One To One

Lets look at the picture what does it mean to be “One-To-One” relationship.

1 to 1 relationship

To make it short lets look at these points;

  • One person(User in my) has one passport
  • passport can’t be shared by other people
  • passport is belongs to a person

According to the points stated, how do we translate that into laravel ORM implementation? Lets try it out.

For legacy database, we are required to specify the link between tables manually. In this example put your attention on User.php at passport() method, and Passport.php on user()

  • In both methods, I place “passport_number” twice after the model name.
  • Please be notice that “passport_number” is the primary key of the Passport model, but it become the foreign key on the User model.
  • In legacy database design, we need to specify both “foreign_key”, “local_key” to override the laravel convention when initiating the model relationship.

If we try to access it in “php artisan tinker”, the expected output should be as follows:

The output shows that data can be retrieved in both from passport and user model.

This article will be continued in part 2, for other relationship term.

Thanks for reading.

--

--

Jurin Liyun

Developer, Trainer , Consultant, Father of two children