Reputation: 183
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
Upvotes: 0
Views: 3453
Reputation: 1263
Firstly relation comes with eager loading. Please update your codes according to single usage
In Product Model
public function category()
{
return $this->belongsTo('App\Category');
}
In Controller
$products = Product::with('category')->get();
dd($products[0]->category);
Upvotes: 3
Reputation: 364
You are telling relationships name is categories
, so laravel belongsTo
will look categories_id
instead category_id
.
You can rename your relationships name as category()
or
give your relationships foreign key to laravel like this;
return $this->belongsTo('App\Category', 'category_id', 'id');
Upvotes: 2