1

I have a polymorphic model Discussion and other models that are discussable.

I have configured my morph map to translate project to App\Models\Company\Project which is discussable.

I would like to write:

function get_all_discussions($type, $id) 
{
    return Discussion::orderBy('created_at', 'desc')
        ->where('discussable_type', $type)
        ->where('discussable_id', $id)
        ->get();
}

get_all_discussion('project', 1232);

Unfortunately ->where('discussable_type', $type) does not work with the morph map.

My current solution is to use this kludge:

function getMorphType($typeOrClass)
{
    $morphMap = array_flip(\Illuminate\Database\Eloquent\Relations\Relation::morphMap());

    return array_get($morphMap, $typeOrClass, $typeOrClass);
}
nowox
  • 25,978
  • 39
  • 143
  • 293
  • Have you added the `morphMap` before or after already having instances of `Discussion`? Check your database and see whether the full class name is filled in or just `'project'`. If the full class name is filled in it is probably fixed by replacing the full class names with the shorthand names. – Teun Jun 04 '19 at 14:57
  • @Teun `morphMap` is created in my `AppServiceProvider@boot` – nowox Jun 04 '19 at 15:12
  • What do you mean by "does not work with the morph map"? The `discussable_type` column already contains "projects" instead of "App\Models\Company\Project", right? – Jonas Staudenmeir Jun 04 '19 at 20:28

1 Answers1

-1

A better approach could be defining relationships in the models: https://laravel.com/docs/5.8/eloquent-relationships#polymorphic-relationships

For example I got Project and Issue, two models that could be discussable.

class Project
{
    public function discussions()
    {
        return $this->morphMany(Discussion::class, 'discussable');
    }
}
class Issue
{
    public function discussions()
    {
        return $this->morphMany(Discussion::class, 'discussable');
    }
}

Then if you want to get all discussion for a project or an issue:

$project = Project::findOrFail(101);
$issue = Issue::findOrFail(102);

$project->discussions;
$issue->discussions;
Kevin Bui
  • 2,754
  • 1
  • 14
  • 15