PHP code example of staudenmeir / laravel-merged-relations

1. Go to this page and download the library: Download staudenmeir/laravel-merged-relations 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/ */

    

staudenmeir / laravel-merged-relations example snippets


class Tag extends Model
{
    public function allTaggables()
    {
        // TODO
    }

    public function posts()
    {
        return $this->morphedByMany(Post::class, 'taggable');
    }

    public function videos()
    {
        return $this->morphedByMany(Video::class, 'taggable');
    }
}

class User extends Model
{
    public function allComments()
    {
        // TODO
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function postComments()
    {
        return $this->hasManyThrough(Comment::class, Post::class);
    }
}

use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createMergeView(
    'all_taggables',
    [(new Tag)->posts(), (new Tag)->videos()]
);

use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createMergeViewWithoutDuplicates(
    'all_comments',
    [(new User)->comments(), (new User)->postComments()]
);

use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createOrReplaceMergeView(
    'all_comments',
    [(new User)->comments(), (new User)->postComments()]
);

use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::renameView('all_comments', 'user_comments');

Schema::dropView('all_comments');

class Tag extends Model
{
    use \Staudenmeir\LaravelMergedRelations\Eloquent\HasMergedRelationships;

    public function allTaggables(): \Staudenmeir\LaravelMergedRelations\Eloquent\Relations\MergedRelation
    {
        return $this->mergedRelation('all_taggables');
    }
}

class User extends Model
{
    use \Staudenmeir\LaravelMergedRelations\Eloquent\HasMergedRelationships;

    public function allComments(): \Staudenmeir\LaravelMergedRelations\Eloquent\Relations\MergedRelation
    {
        return $this->mergedRelationWithModel(Comment::class, 'all_comments');
    }
}

$taggables = Tag::find($id)->allTaggables()->latest()->paginate();

$users = User::with('allComments')->get();

use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createMergeView(
    'all_taggables',
    [
        (new Tag)->posts()->withPivot('tagged_at'),
        (new Tag)->videos()->withPivot('tagged_at'),
    ]
);

$taggables = Tag::find($id)->allTaggables;

foreach ($taggables as $taggable) {
    dump($taggable->pivot->tagged_at);
}

protected bool $dropViews = true;