CakePHP to Laravel migration guide

As a developer who has been using CakePHP for quite a few years, now I’m starting to develop apps with Laravel. This is something I’ve been wanting to do for awhile now, and I’m having my ups and downs, but one of things I thought might be useful, is to have something of a migration guide for developers who already know their way around CakePHP.

There are a lot of similarities, and if you’ve worked with Cake’s ORM, you will find Eloquent quite familiar. The first big difference hit me pretty hard, and its with the way Eloquent handles relationships, which is very different from Cake. Lets take this simple example:

We have two models. Users and Articles. Users will haveMany Articles, and Articles will belongTo Users. In our database this will be modeled with two tables: users and articles. On our articles table we will add a field: user_id and make a foreign key that references articles. So far, this is pretty standard, and something you would expect to do on a “Hello World” application of either framework. Lets see how we would model these in Cake and Laravel. In both cases we will rely on conventions as much as possible to avoid writing too much boilerplate code.

CakePHP’s Table and Model

In Cake, we need to make a Table and an Entity. While a table will represent a collection of users an Entity will be only one specific one. Lets see how the code looks.

Nice and short! In Cake, relationships are defined in Table classes. They are also were validation logic, behaviors and custom finders are used. The Entity is the place you go if you need accessors and mutators, field guards, or other custom logic that would apply for a single entity. In Laravel, the placement of these things are very different, and in my oppinion are more similar to older CakePHP 2.x applications, where there was no separation of Tables and Entities.

Laravel Eloquent

Now lets try to achieve the same result in Laravel. All we need to do is extend the eloquent model, and define our relationships as functions.

And that’s it! Laravel doesn’t actually keep a list of each model’s relationships like Cake, it simply lazy loads them, if needed. Lets take a look and compare how we would do some queries with each framework using the models we have just created.

To be continued…

CakePHP vs Laravel

Custom findersLocal Scopes
BehaviorsGlobal Scopes
CakePHP terms in Laravel

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.