Skip to content

zingimmick/laravel-eloquent-relationships

Repository files navigation

Laravel Eloquent Relationships

Build Status Code Coverage Latest Stable Version Total Downloads Latest Unstable Version License

Requirements

Require Laravel Eloquent Relationships using Composer:

composer require zing/laravel-eloquent-relationships

Usage

BelongsToOne

BelongsToOne is based on BelongsToMany

Difference:

  • returns related model instead of collection of models
  • returns null instead of empty collection of models if the relationship does not exist
  • supports return default related model in case the relationship does not exist

Example:

<?php

use Illuminate\Database\Eloquent\Model;
use Zing\LaravelEloquentRelationships\HasMoreRelationships;
use Zing\LaravelEloquentRelationships\Relations\BelongsToOne;
use Zing\LaravelEloquentRelationships\Tests\Models\User;

class Group extends Model
{
    use HasMoreRelationships;

    public function leader(): BelongsToOne
    {
        return $this->belongsToOne(User::class)
            ->wherePivot('status', 1)
            ->withDefault(function (User $user, self $group): void {
                $user->name = 'leader for ' . $group->name;
            });
    }
}

MorphToOne

MorphToOne is based on MorphToMany

Difference:

  • returns related model instead of collection of models
  • returns null instead of empty collection of models if the relationship does not exist
  • supports return default related model in case the relationship does not exist

Example:

<?php

use Illuminate\Database\Eloquent\Model;
use Zing\LaravelEloquentRelationships\HasMoreRelationships;
use Zing\LaravelEloquentRelationships\Relations\MorphToOne;
use Zing\LaravelEloquentRelationships\Tests\Models\Product;

class Image extends Model
{
    use HasMoreRelationships;

    public function bestProduct(): MorphToOne
    {
        return $this->morphedByOne(Product::class, 'imageable', 'model_has_images');
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Zing\LaravelEloquentRelationships\HasMoreRelationships;
use Zing\LaravelEloquentRelationships\Relations\MorphToOne;
use Zing\LaravelEloquentRelationships\Tests\Models\Image;

class Product extends Model
{
    use HasMoreRelationships;

    public function cover(): MorphToOne
    {
        return $this->morphToOne(Image::class, 'imageable', 'model_has_images')->withDefault([
            'url' => 'https://example.com/default.png',
        ]);
    }
}

License

Laravel Eloquent Relationships is an open-sourced software licensed under the MIT license.

About

More eloquent relationships for Laravel

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages