Skip to content

awssat/laravel-kabsa

Repository files navigation

Laravel Kabsa 🍗

Latest Version on Packagist Software License Build Status Quality Score Total Downloads

Laravel Kabsa is a simple array trait for your Eloquent model just like https://github.com/calebporzio/sushi without SQLite

Install

To get started with Laravel Kabsa, use Composer to add the package to your project's dependencies:

composer require awssat/laravel-kabsa

Examples

Code examples available see: examples

Use

  1. Add the Kabsa trait to a model.
  2. Add a $rows property to the model.
class State extends Model
{
    use \Awssat\Kabsa\Traits\Kabsa;

    protected $rows = [
        [
            'abbr' => 'NY',
            'name' => 'New York',
        ],
        [
            'abbr' => 'CA',
            'name' => 'California',
        ],
    ];
}

or

class State extends Model
{
    use \Awssat\Kabsa\Traits\Kabsa;

    public function getRows() 
    {
        return [
            [
                'abbr' => 'NY',
                'name' => 'New York',
            ],
            [
                'abbr' => 'CA',
                'name' => 'California',
            ],
        ];
    }
}

Now, you can use this model anywhere you like, and it will behave as if you created a table with the rows you provided.

$stateName = State::where('Abbr', 'NY')->first()->name;

// or
$stateName = State::firstWhere('Abbr', 'NY')->name;

Relationships

class Role extends Model
{
    use \Awssat\Kabsa\Traits\Kabsa;

    protected $rows = [
        ['label' => 'admin'],
        ['label' => 'manager'],
        ['label' => 'user'],
    ];
}

You can add a relationship to another standard model with help of new trait called KabsaRelationships right now I have just added two relationships hope we add more

class User extends Model
{
    use \Awssat\Kabsa\Traits\KabsaRelationships;

    public function role()
    {
        return $this->belongsToKabsaRow(Role::class, 'role_label', 'label');
    }
}

the users table should have a role_label column, then:

// Grab a User.
$user = User::first();
// Grab a Role.
$role = Role::where('label', 'admin')->first();

// Associate them.
$user->role()->associate($role);

// Access like normal.
$user->role;

Eager loading doesn't work because it's a collection you don't need eager load you can call the relation ->relation directly. If you need it to be appended to the collection array you can create an attribute and add it to $appends.

License

The MIT License (MIT). Please see License File for more information.