zing / laravel-eloquent-relationships
More eloquent relationships for Laravel
Fund package maintenance!
www.paypal.com/paypalme/zingimmick
Installs: 14 100
Dependents: 0
Suggesters: 0
Security: 0
Stars: 8
Watchers: 2
Forks: 0
Open Issues: 1
Requires
- php: ^8.0
- illuminate/database: ^8.69 || ^9.0 || ^10.0 || ^11.0
- illuminate/support: ^8.69 || ^9.0 || ^10.0 || ^11.0
Requires (Dev)
- mockery/mockery: ~1.3.3 || ^1.4.2
- nunomaduro/larastan: ^1.0 || ^2.0
- orchestra/testbench: ^6.0 || ^7.0 || ^8.0 || ^9.0
- phpunit/phpunit: ^9.3.3 || ^10.0 || ^11.0
- zing/coding-standard: ^6.4 || ^7.0
README
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.