PHP code example of zing / laravel-eloquent-relationships

1. Go to this page and download the library: Download zing/laravel-eloquent-relationships library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zing / laravel-eloquent-relationships example snippets




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;
            });
    }
}



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');
    }
}



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',
        ]);
    }
}