Im tru to use to last version of laravel and i have small problem with Laravel relationship One to Many
Im try to connect products with categories
This is my code of Product model
public function categories()
{
return $this->belongsTo('App\Category');
}
this is my code of Category model
public function products()
{
return $this->hasMany('App\Product');
}
This is my code in controller
$products = Product::with('categories')->get();
dd($products);
this is my code from migration files
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('keywords')->nullable();
$table->string('price');
$table->text('description')->nullable();
$table->text('image')->nullable();
$table->timestamps();
$table->foreign('category_id')->references('id')->on('categories');
});
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('keywords')->nullable();
$table->timestamps();
});[![enter image description here][1]][1]
If someone know how to solved this problem I'll be very grateful
belongsTo()returns a single record ornull. The namecategoriessuggests many (it's plural). Change the name tocategory, or change the method tohasMany()orbelongsToMany(). You should never use a plural name for single records, or a singular name for multiple records._followed by the name of the primary key column. So I think eloquent is determinig that the fk iscategories_idinteadcategory_idCategoryshould be correctly mapped tocategory_id. Ah; maybe not, but the method name is wrong; should becategory()notcategories()for abelongsTo()orhasOne()method.categoryand notcategoriessince it's abelongsTorelationship. I just copied what is in the documentation regarding One To Many (Inverse). Eloquent will take the "snake case" name of the owning model and suffix it with_idfor hasMany and hasOne relationshps, but for belogsTo, will examine the name of the relationship method. The other thing I added to the comment is just a guess, it could also give an exception by not finding the column.