Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

evgenroev's avatar

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories_id' in 'field list' (SQL: insert into `categories_product` (`categories_id`, `product_id`) values (4, 1))

at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671 667| // If an exception occurs when attempting to run a query, we'll format the error 668| // message to include the bindings with SQL, which will make this exception a 669| // lot more helpful to the developer instead of just the database's errors. 670| catch (Exception $e) {

671| throw new QueryException( 672| $query, $this->prepareBindings($bindings), $e 673| ); 674| } 675|

• A column was not found: You might have forgotten to run your migrations. You can run your migrations using php artisan migrate. https://laravel.com/docs/master/migrations#running-migrations

  +12 vendor frames 

13 database/seeds/ProductTableSeeder.php:29 Illuminate\Database\Eloquent\Relations\BelongsToMany::sync()

  +1 vendor frames 

15 database/seeds/ProductTableSeeder.php:30 Illuminate\Support\Collection::each()

class ProductTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { factory(Product::class, 120)->create(); $faker = Factory::create();

    Product::all()->each(function ($product) use ($faker){
       $product->slug = Str::slug($product->title, '-');
       $product->save();

       $categories = [];

       for ($i =0; $i<4; $i++) {
           array_push($categories, $faker->numberBetween(1, 5));
       }

       $product->categories()->sync($categories);
    });
}

}

?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Models\Product; use Faker\Generator as Faker;

$factory->define(Product::class, function (Faker $faker) { return [ 'title' =>$faker->numerify('Product ###'), 'description' => $faker->paragraphs(4, true), 'price' => $faker->randomFloat(2, 10, 999), 'barcode' =>$faker->ean8, 'stock' =>$faker->numberBetween(0, 999), 'cover' =>'https://loremflickr.com/640/480/computer' ]; });

lass CreateCategoriesProductTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('categories_product', function (Blueprint $table){ $table->bigInteger('category_id'); $table->bigInteger('product_id'); });

}
0 likes
1 reply
faridbabayev's avatar

@evgenroev Edit your categories relation method inside Product model. Like that

$this->belongsToMany('App\Category', 'categories_product', 'product_id', 'category_id');

Please or to participate in this conversation.