An open API service indexing awesome lists of open source software.

https://github.com/zingimmick/laravel-eloquent-relationships

More eloquent relationships for Laravel
https://github.com/zingimmick/laravel-eloquent-relationships

eloquent laravel relationships

Last synced: about 1 month ago
JSON representation

More eloquent relationships for Laravel

Awesome Lists containing this project

README

        

# Laravel Eloquent Relationships


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

## Requirements

- [PHP 8.0+](https://php.net/releases/)
- [Composer](https://getcomposer.org)
- [Laravel 8.69+](https://laravel.com/docs/releases)

Require Laravel Eloquent Relationships using [Composer](https://getcomposer.org):

```bash
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
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
morphedByOne(Product::class, 'imageable', 'model_has_images');
}
}
```

```php
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](LICENSE).