morphTo Last updated: 2023-03-27

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

Here we will explain how to bring one value through morphTo

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

we have two models to add a new value by App\Models\User OR App\Models\Admin

Inside the comments 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();
	}
}

 

Note that we have prepared the method owner in Comment Model

You will use this relation method to add value by Admin OR User Using Resource 

morphTo()->make('Add By', 'owner')
  ->types([
	 \App\Dash\Resources\UsersResource::class ,
	 \App\Dash\Resources\AdminsResource::class , 
 ]), 
 // you can add more resource to get Models with Ids to add who is comment

Label : Add By

method: owner

reference resources is : App\Dash\Resources\UsersResource & App\Dash\Resources\AdminsResource

now after run this in  App\Dash\Resources\Comment Resource 

you got dropdown to choose Model And Id

 

also you can custom query with specific Resource if you want to do that just add anonymous function and write your query

example with `UsersResource

morphTo()->make('Add By', 'owner')
  ->types([
	 [\App\Dash\Resources\UsersResource::class ,function($model){
	 	return $model::where('user_status','active'); // your query on User Model
	 }],
	 \App\Dash\Resources\AdminsResource::class , 
 ]), 
 // you can add more resource to get Models with Ids to add who is comment