Custom Polymorphic Types

Laravel 預設會以完整的 class name 來當作 polymorphic model 的值。例如:

+--------+-------------+---------------+
| tag_id | taggable_id | taggable_type |
+--------+-------------+---------------+
| 1      | 1           | App\Post      |
+--------+-------------+---------------+
| 2      | 1           | App\Video     |
+--------+-------------+---------------+

不過,如果不想要這麼長的 class name 當作名稱的話,也可以另外自訂。在 AppServiceProvider::boot 裡加上下列的程式碼:

use Illuminate\Database\Eloquent\Relations\Relation;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Relation::morphMap([
            'posts' => 'App\Post',
            'videos' => 'App\Video',
        ]);
    }
}

或是另外建立一個 service provider 來做這件事

這樣一來,資料庫裡儲存的值就會變成:

+--------+-------------+---------------+
| tag_id | taggable_id | taggable_type |
+--------+-------------+---------------+
| 1      | 1           | posts         |
+--------+-------------+---------------+
| 2      | 1           | videos        |
+--------+-------------+---------------+

參考: