Share Laravel Eloquent Models Between Multiple Applications

Ambuj Soni
5 min readOct 23, 2020

Introduction

Laravel is a widely adopted framework across industries at any scale. It is not only user-friendly but it also ships along with some powerful features and Eloquent Object Relational Mapper (ORM) is just one of them.

While working with large scale applications, they tend to become too large to deal with (monolithic), thus often it becomes necessary to break them into separate small applications (micro-services). It is a worthwhile journey, but not an easy one.

The Problem

During the breakdown process, developers create multiple Laravel applications and define Models (logical structure and relationship of underlying tables) in each individual application which enables them to interact with database tables.
Now the problem occurs when developers have to create the exact same Models in each individual application repeatedly and this becomes even worse when they need to publish any modifications in Models. One obvious approach is to make changes manually on all microservices separately, which is not only inefficient, it can turn out to be a nightmare for developers.

A Rational Solution

The ideal solution to tackle this problem is to separate the ‘Model Logic Layer’ from all applications and serve as a separate package. Then other Laravel applications can import this package as a Composer dependency.
In the end, all you need to do is ‘composer install’ or ‘composer update’ for other applications, and you are done!

Steps

Prerequisite

  • Composer
  • Laravel
  • GitHub Account

Step 1: Setup a Laravel project

You can skip this step if you already have a Laravel project ready where you want to consume Shared Laravel Models.

For our demo, we will create a blank blog application:

composer create-project --prefer-dist laravel/laravel blog

Once the installation is completed, setup the .env file to configure the database connection.

Step 2: Setup our ‘Shared Laravel Model’ package

  1. Create a new folder and name it ‘laravel-shared-models’.
  2. Inside this folder create a new file called ‘composer.json’ with the following content.
{
"name": "<your-git-username>/<app-name>-models",
"type": "library",
"description": "Your package description goes here",
"homepage": "https://yourcompany.com",
"authors": [
{
"name": "<author-full-name>",
"email": "<author-email-id>",
"role": "<author-role>"
}
],
"autoload": {
"psr-4": {
"<ProjectName>\\SharedModels\\": "src"
}
}
}

Note ‘your-git-username’, ‘app-name’, and ‘ProjectName’ as they are crucial and required in later steps.

For this demo, the values will be:

  • git-username: johndoe
  • app-name: blog
  • ProjectName: BlogApp

3. Next, inside the same folder, create a subfolder and name it ‘src’ which will hold all our Eloquent Models.

4. Now, inside this ‘src’ folder create your first model.
For this demo, we will add only a ‘User’ model. You can get the raw codes from Laravel’s official git repository.
https://github.com/laravel/laravel/blob/master/app/Models/User.php

Package Directory Structure

Now an important point to note:
By default, this User model will be on namespace ‘App\Models’ (line no. 3), whereas our package does not work in this namespace. Thus, replace this line with your package’s namespace as mentioned in the composer.json file under psr-4 value.

namespace <ProjectName>\SharedModels;
namespace BlogApp\SharedModels;

Lastly, if you have any custom configuration, just add them and that’s it, we are done with our first model. Similarly, you can add other models as well inside ‘src’ folder.

Step 4: Publish your Package

In order to consume our Shared Laravel Models, we need to publish them, such that the composer can install them as a dependency.

There are various options for this:

  • Packagist
  • Public Git Repository
  • Private Git Repository

Since most of the developers might be working on private projects and repositories, in this demo we will publish our package as ‘Private Git Repository’ on Github.

Login to your Github account and create a new git repository and push your ‘laravel-shared-models’ codes.

It is extremely necessary that the value of ‘name’ attribute mentioned in your composer.json must match your repository name.
<your-git-username>/<app-name>-models

For example:
Based on the values mentioned earlier our name should be:
johndoe/blog-models

And similarly, after publishing on git, the repository URL should be:
https://github.com/johndoe/blog-models.git

Step 5: Add your GitHub package as composer dependency

Open the composer.json file of your Laravel project (in our case blog app) and make the following changes:

  1. Add your package dependency by mentioning it inside the “require” attribute.

2. Provide a reference to your git repository so that the composer can find your package.

{
"require": {
"<your-git-username>/<app-name>-models": "dev-master"
},
"repositories": [
{
"type": "vcs",
"url": "git@github.com:<your-git-username>/<app-name>-models.git"
}
]
}

and for our demo it should look like:

{
"require": {
"johndoe/blog-models": "dev-master"
},
"repositories": [
{
"type": "vcs",
"url": "git@github.com:johndoe/blog-models.git"
}
]
}

3. Since the git repository is private, the composer will not be able to fetch the codes automatically, thus we need to provide it some access. There are two ways to achieve it:

  • using auth.json file
  • using SSH keys

For our demo, we will be using ‘auth.json’ file. However, if you want to explore another option visit https://srinathdudi.com/composer-github-private-repositories/

Inside your Laravel project’s root directory, create a blank file called ‘auth.json’ and add the following code:

{
"github-oauth": {
"github.com": "your-github-token"
}
}

Generate GitHub Token:

  1. Log in to your GitHub account
  2. Go to Settings ➨Developer Settings ➨Personal Access Tokens
  3. Generate a new Token, and make sure you provide only ‘read’ access to it.
  4. Now, add your token in the auth.json file.

Make sure you mentioned auth.json in .gitignore file to prevent it from uploading on the repository.

And here we are done!

Just run ‘composer update’ for your Laravel app and the composer should download your package as a dependency.

Step 6: Consume Shared Models

Now in your Laravel application, you just need to change the package import.
From:

use App\Models\User;

To:

use <ProjectName>\SharedModels\User;

Example:

use BlogApp\SharedModels\User;class UserController extends Controller
{
public function getOneUser()
{
$users = User::first();
}
}

Alternatively, if you are using a public git repository, again you can follow the same process, just skip generating the auth.json file.

And, if you want to publish your package on Packagist, read https://www.w3resource.com/php/composer/create-publish-and-use-your-first-composer-package.php?passed=passed.

Remember, you should never publish your Laravel Models as public. It can expose your database layer and make your app vulnerable.

--

--