0

I have just created a many-to-many relationship between the models Project and Features using Laravel however I receive the following error when attempting to run the seed script.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'table.feature_projects' doesn't exist 

The table in use is named features_project which is the default name given.

Inserting the seed data manually does return the relational data to the view as expected.

SEED

class FeaturesProjectTableSeeder extends Seeder
{

public function run()
{
    $features_project = new \App\FeatureProject ([
        'project_id' => '1',
        'features_id' => '1'
    ]);
    $features_project->save();
}
}

Project

<?php 
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model {
        
        public function features() {
        return $this->belongsToMany('App\Features')->withTimestamps();
    }
}

Features

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Features extends Model
{
    public function projects() {
        return $this->belongsToMany('App\Project')->withTimestamps();
    }
}

CONTROLLER

class ProjectController extends Controller
{

public function getProject($id)
{
    $project = Project::where('id', $id)->get();
    return view('other.project', ['project' => $project]);
}

}

ROUTE

Route::get('project/{id}', [
'uses' => 'ProjectController@getProject',
'as' => 'other.project'
]);

VIEWS

@foreach($project->features as $feature)
 <dd class="col-sm-8">{{ $feature->name }}</dd>
@endforeach
cinameng
  • 313
  • 4
  • 14

1 Answers1

2

Firstly some misunderstanding in naming, your table name should be feature_project, in many to many relationships the models are in alphabetical order. Secondly models are not plural, so your Features.php model should be named Feature.php. Which will resolve in Laravel using the table feature_project for the pivot and features for the model.

For your own sake, learn how Laravel name models and tables, else relationships are gonna be tricky. Which is described in the documentation.

You should not create pivot models, this is handled by assigning features to projects or vice versa. Therefor your seeder should look something like this, it could be you should assign some attributes to the projects and features before it will work.

class FeaturesProjectTableSeeder extends Seeder
{

    public function run()
    {
        $features = factory(Feature::class)->create();

        $projects = factory(Project::class)->create();

        $projects->each(function (Project $project) {
            $project->features()->saveMany($features);
        });
    }
}
mrhn
  • 17,961
  • 4
  • 27
  • 46
  • thanks for the reply, I am new to Laravel yes working my way through the documentation today, The first many to many seed I created worked first time but this one is not working yet – cinameng Aug 09 '20 at 16:54