I am using Laravel’s Eloquent inside a wordpress plugin.
Product Model:
<?php namespace GD;
use Country;
class Product extends IlluminateDatabaseEloquentModel
{
public function country()
{
return $this->belongsTo('Country', 'CountryId');
}
}
Country Model:
<?php namespace GD;
use Product;
class Country extends IlluminateDatabaseEloquentModel
{
public function products()
{
return $this->hasMany('Product');
}
}
I can query any model using standard Laravel syntax:
$products = $this->product->where('MetalId', '=', 1)
->where('ProductTypeId', '=', '2')
->orderBy('Name')->orderBy('CountryId')
->get();
However I am unable to eager/lazy load related models:
$products = $this->product->with('country')->where('MetalId', '=', 1)
->where('ProductTypeId', '=', '2')
->orderBy('Name')->orderBy('CountryId')
->get();
Error Message
Fatal error: Class 'Country' not found in .../vendor/illuminate/database/Illuminate/Database/Eloquent/Model.php on line 593
So I figured that this must be a namespace problem, so I updated my model code to:
return $this->belongsTo('\GD\Country', 'CountryId');
and
return $this->hasMany('\GD\Product');
However when I run the query on the Product Model and vardump the results, I get:
["relations":protected]=>
array(1) {
["country"]=>
NULL
}
I recently had the same problem, and it was indeed a namespace issue.
Try adding only single back-slashes to the namespace strings, since you are using single quotes to enclose them.
Like so:
Also, please ensure that you are using the full namespace. In my app, I used ‘AppModelsModelName’.
Should it be something like ‘AppModelsGDModelName’ for your app? That depends upon your application structure.
Let me know if this works.