PHP code example of nevadskiy / laravel-many-to-morph

1. Go to this page and download the library: Download nevadskiy/laravel-many-to-morph 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/ */

    

nevadskiy / laravel-many-to-morph example snippets


use Nevadskiy\ManyToMorph\HasManyToMorph;
use Nevadskiy\ManyToMorph\ManyToMorph;

class Tag extends Model
{
    use HasManyToMorph;

    public function taggables(): ManyToMorph
    {
        return $this->manyToMorph('taggable');
    }
}

use App\Models\Tag;
use App\Models\Post;
use App\Models\Video;

$tag = Tag::find(1);

foreach ($tag->taggables as $taggable) {
    if ($taggable instanceof Post) {
        // ...
    } else if ($taggable instanceof Video) {
        // ...
    }
}

use App\Models\Tag;

$tag = Tag::find(1);

$tag->taggables()->orderBy('position')->get();

use App\Models\Tag;
use App\Models\Post;
use App\Models\Video;

$tags = Tag::query()
    ->with(['taggables' => function (ManyToMorph $taggables) {
        $taggables->morphWith([
            Post::class => ['media'],
            Video::class => ['previews'],
        ]);
    }])
    ->get();

use App\Models\Tag;
use App\Models\Post;
use App\Models\Video;

$tag = Tag::find(1);

$post = Post::find(1);

$tag->taggables()->attach($post);

$video = Video::find(1);

$tag->taggables()->attach($video, ['score' => 1337]);

use App\Models\Tag;
use App\Models\Video;

$tag = Tag::find(1);

$video = Video::find(1);

$tag->taggables()->detach($video);