0

enter image description hereIm 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

4
  • 1
    belongsTo() returns a single record or null. The name categories suggests many (it's plural). Change the name to category, or change the method to hasMany() or belongsToMany(). You should never use a plural name for single records, or a singular name for multiple records. Commented May 6, 2020 at 18:35
  • 1
    Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the primary key column. So I think eloquent is determinig that the fk is categories_id intead category_id Commented May 6, 2020 at 18:45
  • @porloscerrosΨ I thought it was based off the name of the Model, not the method. Category should be correctly mapped to category_id. Ah; maybe not, but the method name is wrong; should be category() not categories() for a belongsTo() or hasOne() method. Commented May 6, 2020 at 18:47
  • 1
    @TimLewis I agree that the method name should be category and not categories since it's a belongsTo relationship. 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 _id for 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. Commented May 6, 2020 at 19:02

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

6 Comments

While with() is not related to the issue here, saying to remove it is just wrong. If you're loading all Product, then accessing a relationship, you want to use with() to avoid an N+1 query execution issue. Product::with('category')->get(); is the correct syntax here.
Ok updated, I already know this, i just want to show this is not 'with' issue, this is singular plural issue
Yup; make sense. Just keep in mind, you can't use ->all() after another call, you need to use ->get() or you get the error "Call to undefined method Illuminate/Database/Eloquent/Builder::all()", so again, the correct syntax is Product::with('category')->get();
:) this area is not as ide, so i just add with and it is working yay! :) I updated
Haha yeah, that's an easy error to make. Typically, I never use ::all(), since it's not available once chained, and just stick with ::get(), even for all records. Like Product::get() and Product::all() will return the same thing, but Product::with(...)->all(); is an error, where Product::with(...)->get(); is not :)
|
2

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.