morphMany Last updated: 2022-10-04

There is no doubt that sometimes you need to use polymorphismIn your project  

Here we will explain how to bring multiple values through morphMany

Suppose a user can comment on some things using the Model name and user id

App\Models\User

Inside the comment table with morphs owner (owner_type) , (owner_id)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model {
	use HasFactory;

	public function owner() {
		return $this->morphTo();
	}
}

 

And we needed in the user resource to retrieve his  comments

class User extends Authenticatable {
	public function comments() {
		return $this->morphMany(Comment::class, 'owner');
	}
}	

Note that we have prepared the method comments

You will have to fetch the comments inside the user resource this way

morphMany()->make('All Comments', 'comments', Comments::class),

Label : All Comment 

method: comments

reference resource is : App\Dash\Resources\Comment