Search code examples
laravelmany-to-manylaravel-5.3eloquent

Many to many relationship in Laravel


I'm trying to build an application on Laravel 5.3 where my models, database and controllers are in separate folders. I have the following folder structure:

Nitseditor
    System
        Controllers
        Database
            2016_12_28_130149_create_domains_table.php
            2017_01_06_193355_create_themes_table.php
            2017_01_07_140804_create_themes_domains_table.php
        Models
            Domain.php
            Theme.php

I'm making a relationship in domain with many to many relationship i.e.

public function themes()
{
    return $this->belongsToMany('Nitseditor\System\Models\Domain');
}

I've named the table domain_theme inside the 2017_01_07_140804_create_themes_domains_table.php

Now I'm trying to get the theme name which belongs to the domain in the controller something like this:

$flashmesage = new Domain;

foreach ($flashmesage->themes as $theme)
{
    return $theme->theme_name;
}

I'm getting an error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'nitswebbuilder.domain_domain' doesn't exist (SQL: select domains.*, domain_domain.domain_id as pivot_domain_id from domains inner join domain_domain on domains.id = domain_domain.domain_id where domain_domain.domain_id is null and domains.deleted_at is null)


Solution

  • sorry for my short comment as answer... I have not enough reputation for comment,

    change your themes() method to :

    public function themes()
    {
        return $this->belongsToMany('Nitseditor\System\Models\Theme');
    }
    

    see Here for more info