user4655002
user4655002

Reputation:

Why is my Laravel Morphmap returning empty

I have a table like so:

    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('comment_id');
        $table->string('comment_type');
        $table->text('comment');
        $table->timestamps();
    });

Which is populated like so:

INSERT INTO `job`.`comments` (`id`, `user_id`, `comment_id`, `comment_type`, `comment`, `created_at`, `updated_at`) VALUES ('1', '1', '8', 'courses', 'Hello', NULL, NULL);

I have a course model like so:

<?php

namespace App\Modules\Courses\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Laravelista\Comments\Comments\Traits\Comments;

class Courses extends Model
{
    use Comments;

    protected $table = 'courses';

    public function comments()
    {
        return $this->morphMany('App\Modules\Comments\Models\Comments', 'comment');
    }

which morphs my Comment model with my Morph map:

<?php

namespace App\Modules\Comments\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;

Relation::morphMap([
    'courses' => App\Modules\Courses\Models\Courses,
]);

class Comments extends Model
{
    public function commentable()
    {
      return $this->morphTo();
    }
}

If I reference my map in my row and use courses at the type it returns empty as you can see from Tinker:

enter image description here

But if I use the full namespace in the comment_type in the database it works:

INSERT INTO `job`.`comments` (`id`, `user_id`, `comment_id`, `comment_type`, `comment`, `created_at`, `updated_at`) VALUES ('1', '1', '8', 'App\\Modules\\Courses\\Models\\Courses', 'Hello', NULL, NULL);

enter image description here

What am I doing wrong, and how can I fix this?

edit: I have also tried the suggestions of placing it inside my app service provider too, but that didn't work neither:

enter image description here

Upvotes: 1

Views: 1193

Answers (1)

OuailB
OuailB

Reputation: 1119

Try to register the Relation::morphMap() in a Service Provider

AppServiceProvider

use Illuminate\Database\Eloquent\Relations\Relation;
...
public function boot()
{
    Relation::morphMap([
         'courses' => 'App\Modules\Courses\Models\Courses',
    ]);
}

https://laravel.com/docs/5.4/eloquent-relationships#polymorphic-relations

Upvotes: 1

Related Questions