• Stars
    star
    147
  • Rank 250,396 (Top 5 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Allows you to decouple your eloquent models from one another.

Eloquent Relativity

This allows you to decouple your eloquent models from one another, by defining relations dynamically at run-time.

- Note that this package is NOT needed in laravel 7.x or above.

Read more: https://laravel.com/docs/7.x/eloquent-relationships#dynamic-relationships

widgetize_header

Build Status Scrutinizer Code Quality Code Coverage Latest Stable Version StyleCI Total Downloads

Compatibility :

Laravel version 5.5 and above including version 6

▶️ A problem which stops true modularity :

Let's face it, imagine you have a modular blog application.

Then, you want to add a commenting feature to it, so that users can comment on your articles.

In a modular structure, you have 2 modules (user module and blog module) and you will add a new module for comments

▶️ let's analyze dependencies and couplings :

Here the blog module "knows" and "depends" upon the user module.

But the user module should not know or care about the blog module. The blog is a plug-in on the top of the user module.

Now we want to add a comment module, on the top of user and blog module.

▶️ The Right way :

In a truely modular system when you add the comments, you should NOT go and touch the code within the users or blog module. (Remember the open-closed principle in SOLID ?!)

Imagine you are in a team and each member is working on a seperate module.

Blog module is not yours. your team mate is responsible for it and is allowed to code on it.

But when you want to start to define the eloquent relations between Comment and User and Article models, you immediately realize that you have to put code on the eloquent models of other modules to define the inverse of the relationships. Crap !

Look How everything is pointing inward.

If you look at the User folder you will have absolutely no footprint of Comment or Article.

We have to touch the code of both Blog and User module when add a new comment module.

For example : You have to open User.php and define the

public function comments() {
    return $this->hasMany(Comment::class); 
}

and this is a no no, because it makes an arrow from inside to outside.

So what to do ?!

How can Comment be introduced to the system without modifying the other modules ?! (@_@)

▶️ Install: (the most painful step)

composer require imanghafoori/eloquent-relativity   (and take a coffee...)

Now the installtion finished, you first have to make your models "relative" !!!

By using the Imanghafoori\Relativity\DynamicRelations traits on your eloquent models.

image

So the User, Article, Comment will have to have this trait one them.

Now comes the sweet part :

within the CommentsServiceProvider.php

class CommentsServiceProvider 
{
    public function register () {
        
        User::has_many('comments', Comment::class);     // instead of defining method on the User class.
        Article::has_many('comments',  Comment::class);
        
        Comment::belongs_to('author', User::class);       // inverse of relations
        Comment::belongs_to('article',  Article::class);
    }

}

Now you can do these queries :

User::find(1)->comments;
or 
User::find(1)->comments()->count();

So instead of going to User model and define a method there...

public function comments() {
    return $this->hasMany(Comment::class); 
}

You have defined the method remotely from your new module at run-time:

User::has_many('comments', Comment::class);

Here is a list of supported relations :

  • has_many
  • has_one
  • belongs_to
  • belongs_to_many
  • morph_to_many
  • morph_many
  • morph_one
  • morph_to
  • morphed_by_many
  • has_many_through

They accept the same paramters as the eloquent equivalent counter part. except the first argument should be relation name.

▶️ Extra features :

sometimes you need to call extra methods on the relations.

User::has_many('comments', Comment::class)->orderBy('id', 'asc');

All the methods are available to you.

  • Enforce eager-loading

On reqular eloquent models you may define the

User extends Model {
    protected $with = ['comments'];
}

instead you can :

User::forceEagerLoading('comments');

remember this should be in the boot method of your Service Provider not the register method.

Your Stars Make Us Do More

As always if you found this package useful and you want to encourage us to maintain and work on it, Please press the star button to declare your willing.

▶️ More from the author:

Laravel Terminator

💎 A minimal yet powerful package to give you opportunity to refactor your controllers.


Laravel Widgetize

💎 A minimal yet powerful package to give a better structure and caching opportunity for your laravel apps.


Laravel Master Pass

💎 A simple package that lets you easily impersonate your users.


Laravel HeyMan

💎 It allows to write exressive and defensive code which is decoupled from the rest of your app.


🍌 Reward me a banana 🍌

so that I will have energy to start the next package for you.

Dodge Coin: DJEZr6GJ4Vx37LGF3zSng711AFZzmJTouN

LiteCoin: ltc1q82gnjkend684c5hvprg95fnja0ktjdfrhcu4c4

BitCoin: bc1q53dys3jkv0h4vhl88yqhqzyujvk35x8wad7uf9

Ripple: rJwrb2v1TR6rAHRWwcYvNZxjDN2bYpYXhZ

Etherium: 0xa4898246820bbC8f677A97C2B73e6DBB9510151e


Life is like riding a bicycle. To keep your balance you must keep moving.

"Albert Einstein"

More Repositories

1

laravel-microscope

Fearless refactoring, it does a lot of smart checks to find certain errors.
PHP
1,307
star
2

laravel-widgetize

A minimal package to help you make your laravel application cleaner and faster.
PHP
902
star
3

laravel-heyman

Declarative style of authorization and validation in laravel.
PHP
880
star
4

laravel-MasterPass

Helps you securely setup a master password and login into user accounts with it.
PHP
354
star
5

laravel-terminator

A package to help you clean up your controllers in laravel
PHP
246
star
6

laravel-video

A laravel package to stream video content.
PHP
232
star
7

laravel-anypass

A minimal package that helps you login with any password on local environments
PHP
211
star
8

laravel-decorator

Easily decorate your method calls with laravel-decorator package
PHP
129
star
9

eloquent-mockery

Mock your eloquent queries without the repository pattern
PHP
123
star
10

laravel-middlewarize

Use middleware to decorate method calls within your application code.
PHP
105
star
11

laravel-nullable

Functional programming paradigms in laravel to avoid run-time errors.
PHP
102
star
12

laravel-temp-tag

Temporarily and Transparently, tag your eloquent models
PHP
100
star
13

laravel-smart-facades

Strategy design pattern in laravel, the easiest way.
PHP
87
star
14

laravel-password-history

Keep a password history of your users to prevent them from reusing the same password.
PHP
64
star
15

iranian-laravel-contributors

The list of people from Iran who have contributed to the laravel framework
40
star
16

laravel-tokenized-login

Two factor authentication in Laravel
PHP
36
star
17

eloquent-history

PHP
31
star
18

smart-realtime-facades

PHP
30
star
19

php-smart-search-replace

Smart search/replace functionality for PHP code
PHP
27
star
20

gilded_rose

Based on a tutorial for code refactoring
PHP
25
star
21

why_github_is_not_open_source

Why github.com is NOT open-source???
25
star
22

laravel-makesure

Readable syntax to write tests in laravel
PHP
21
star
23

eloquent-rating

5 star rating for eloquent models
PHP
18
star
24

laravel-file-cache-cleaner

Delete the obsolete cache files in the storage directory
PHP
15
star
25

php_token_analyzer

PHP
11
star
26

laravel-db-freeze

A package that allows you to bypass any insert, edit, delete into your database in demo mode through .env variables
10
star
27

laravel-anytoken

A minimal development package that helps you fake any api token as a valid one during development
10
star
28

composer-json

A utility class for read composer.json data and use it in PHP
PHP
9
star
29

crudbooster-statistics

Statistics module for Crudbooster CMS
HTML
8
star
30

imanghafoori1

8
star
31

laravel-microscope-ui

8
star
32

laravel-tik8

Simple modular ticketing system by laravel
8
star
33

crudbooster-logs

A plug-in for CrudBooster CMS to add log functionality
PHP
8
star
34

chat

node chat application
HTML
7
star
35

crudbooster-notifications

Adds notification functionality to crudbooster
PHP
7
star
36

laravel-nice-middlewares

This is a plug-in for laravel-middlewarize package.
PHP
6
star
37

questionist

Advanced event/listener system
PHP
6
star
38

abstract_php_filesystem

PHP
3
star
39

example_query

PHP
2
star
40

test-bin

1
star
41

laravel-endpoints

Define your endpoints as classes
1
star
42

git_toturial

1
star