Home » Php » php – Laravel – Eloquent Relationship not working One to Many relationship

php – Laravel – Eloquent Relationship not working One to Many relationship

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have two models with One-to-Many relationship. I want to display data with relationship in blade.

Products Table

Table name = Products
PrimaryKey = pro_id
ForeignKey = cat_id

Categories Table

Table name = categories
PrimaryKey = cat_id

Products Model Code

namespace App;

use Illuminate\Database\Eloquent\Model;

class productsModel extends Model
{
    //code...
    protected $table      = 'products';
    protected $primaryKey = 'pro_id';

    // Every Products Belongs To One Category

    public function category()
    {
        # code...
        return $this->belongsTo('APP\abcModel','cat_id');
    }
}

Categories Model Code

namespace App;

use Illuminate\Database\Eloquent\Model;

class categoryModel extends Model
{
    //code...
    protected $table      = 'categories';
    protected $primaryKey = 'cat_id';

    // One Category Has Many Products

    public function products()
    {
        # code...
        return $this->hasMany('App\productsModel','cat_id','pro_id');
    }
}

Controller Code

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\productsModel;
class productsController extends Controller
{
    //code...
    public function products($category_id='')
    {
        # code...
        $data["products"] = productsModel::where
                            ('cat_id',$category_id)
                            ->get();        
        $data["categories"] = productsModel::where
                            ('cat_id',$category_id)->first()->category;
        echo "<pre>";
        print_r($data);
        echo "</pre>";
    }
}

ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError
Class ‘APP\categoryModel’ not found

How to&Answers:

Seems that sometimes you have App, sometimes APP, while PHP is not case sensitive on class names, you might use an operating system (Linux?) that is case sensitive in terms of file names.

I would recommend to have only App everywhere, your error message clearly indicates: APP.

Answer:

You can clearly see in your model files the namespace is written as “namespace App;
There you defined the namespace for the app folder. So when you are using this model anywhere, you need to write it as you have defined the namespace. Therefore “App\categoryModel“.
Your code should be as follows:

public function category()
{
    # code...
    return $this->belongsTo('App\categoryModel','cat_id');
}

Also a sincere request, as @alithedeveloper mentioned please follow PSR standards for writing code.

Answer:

public function category()
{
    return $this->belongsTo(abcModel::class,'cat_id');
}

public function products()
    {
        return $this->hasMany(productsModel::class,'cat_id');
    }