title: Using Eloquent polymorphic relationships to categorise data in Laravel
body: <p>In my application, I have a categories table, and multiple tables including services and articles that need to be categorised. For convenience, I want to use a polymorphic model for this data.</p>
  
  <p>A category is created to be used by either services or articles. Once a table has been defined as a services table, for example, it is not going to be displayed as a possible category to add articles to.</p>
  
  <p>This also applies to listing. I will have a menu for articles, and a menu for services, and each of these will list just article or service categories, whether they be empty or whether they contain their respective types.</p>
  
  <p>A service category, for example, can be used for many services. Similarly, a service can have many categories - but only service categories.</p>
  
  <p>As it stands, my database is possibly insufficient. I have not used a pivot-table, but when I tried to use one, it didn't allow me to select just article categories or service categories; in fact, it couldn't differ between the two at all.</p>
  
  <p><a href="https://i.stack.imgur.com/ynFkS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ynFkS.png" alt="The schema as it stands."></a></p>
  
  <p>Basically, I need to be able to:</p>
  
  <ul>
  <li>Get a list of all categories usable by services (possibly <code>where('categorizable_type', 'App\Service')</code>?)</li>
  <li>Get a list of all categories usable by articles (possibly <code>where('categorizable_type', 'App\Article')</code>?)</li>
  <li>Get a list of all articles/services in a category</li>
  <li>Get a list of all categories used by an article/service</li>
  </ul>
  
  <p>In this ideal situation, I can easily add new (or existing) articles/services to categories, too:</p>
  
  <pre><code>$category = App\Category::find(1);
  $article = new App\Article();
  $article-&gt;title = 'This is an article title.';
  $category-&gt;articles()-&gt;save($article);
  </code></pre>
  
  <p>And I can easily add new (or existing) categories to articles/services:</p>
  
  <pre><code>$article = App\Article::find(1);
  $category = new App\Category();
  $category-&gt;title = 'This is a category title.';
  $article-&gt;categories()-&gt;save($category);
  </code></pre>