patinthehat / laravel-dynamic-relations by patinthehat

dynamic relations for Laravel and Lumen
481
1
3
Package Data
Maintainer Username: patinthehat
Package Create Date: 2017-03-02
Package Last Update: 2020-09-20
Language: PHP
License: MIT
Last Refreshed: 2024-11-15 15:25:06
Package Statistics
Total Downloads: 481
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 1
Total Watchers: 3
Total Forks: 2
Total Open Issues: 0

Laravel DynamicRelations


An extension of Illuminate\Database\Eloquent\Model that allows relationships to be called as dynamic properties, such as:

$prop = "myProp";
$user->$prop->toArray();

####Installation

Install with composer: composer require patinthehat/laravel-dynamic-relations

####Usage

To use, extend the DynamicModel class. In the child class, override the $dynamicRelations array property, adding items that correlate to relation names.

namespace App\Models;

use Permafrost\DynamicRelations\DynamicModel;

class User extends DynamicModel
{
    public static $dynamicRelations = [
      'abc', 'def',
    ];
    
    public function abc()
    {
        return $this->hasMany('App\Models\Abc');
    }
    
    public function def()
    {
        return $this->hasMany('App\Models\Def');
    }
    
}

Now, your relations can be accessed dynamically:

$user = User::find(1);
$prop = "abc";
$user->$prop->toArray();