Require Laravel Eloquent Relationships using Composer:
composer require zing/laravel-eloquent-relationships
BelongsToOne
is based on BelongsToMany
- 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
<?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
is based on MorphToMany
- 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
<?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',
]);
}
}
Laravel Eloquent Relationships is an open-sourced software licensed under the MIT license.