DavidSojka
2 months ago
345
6
Laravel

Relationships between Eloquent models in different folders

Posted 2 months ago by DavidSojka

Hi everyone,

I have two Eloquent models (Product and Category) in different folders and I can't figure out, how to properly make relationship methods between them. This is the folder structure:

| app
|- Product
|- - Category.php
|- Product.php

Now the Product.php looks somehow like this:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
	public function category()
	{
		return $this->belongsTo('App\Product\Category');
	}
}

The Product\Category.php looks like this:

namespace App\Product;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
	public function products()
	{
		return $this->hasMany('App\Product');
	}
}

The last thing you might want to know, is my database (simplified):

product_categories
- int id
- string name

products
- int id
- int product_category_id
- string name

Now my question is, how to make everything work correctly? I usually have problems while saving models into my database, because it can't find the foreign keys (it looks for category_id). What is the easiest way to make it work like this? I have a lot of models and I don't want to keep them just in the app folder.

Please sign in or create an account to participate in this conversation.