morphToMany Last updated: 2022-10-04

There is no doubt that sometimes you need to use polymorphism
In your project and here we will explain how to bring multiple values through morphToMany

Suppose the user want to add posts and videos on some things using the Model name and user id

App\Models\User

Inside the taggables table with morphs taggable (taggable_type) , (taggable_id)

<?php
 

class User extends Authenticatable {
 
 public function posts(){
        return $this->morphedByMany(Post::class, 'taggable'); // is taggables table
    }
    
    
 public function videos(){
        return $this->morphedByMany(Video::class, 'taggable'); // is taggables table
    }
}
 

 

Note that we have prepared the methods posts & videos

You will have to fetch the posts and videos inside the user resource this way

morphToMany()->make('Posts And Videos')
->tags([
	'posts' => App\Http\DashResource\PostsResource::Class,
	'videos' => App\Http\DashResource\VideosResource::Class,
]),

Label : Posts And Videos 

methods: posts& videos

reference resources is : App\Dash\Resources\PostsResource & App\Http\DashResource\VideosResource

 

If you want to assign a name to each resource,

morphToMany()->make('Posts And Videos')
->tags([
	'posts' =>[
		'label'    => 'Your Posts',
		'resource' => App\Http\DashResource\PostsResource::Class,
	],
	'videos'    => [
		'label'    => 'Your Videos', // if not set label can get cusomName method or real resource name
		'resource' => App\Http\DashResource\VideosResource::class,
	],
]),	

 

 

// Video Model
class Video extends Model {

     /**
     * Get all of the Users for the Video.
     */
    public function user()
    {
        return $this->morphToMany(User::class, 'taggable');
    }
}


// post Model
class Post extends Model {

     /**
     * Get all of the Users for the post.
     */
    public function user()
    {
        return $this->morphToMany(User::class, 'taggable');
    }
}

Now everything is clear, do what you want, things are now easy