I'm developing a new laravel 5 application and I'm using eloquent relationships for the first time. I've stumbled upon an issue when creating a relationship.
I have a Purchase model and a User model.
Every purchase is mapped to a user id. So I have a method in the user model to fetch all purchases the user has made and I also have a method in the purchase model to fetch the user that made the purchase.
User:
public function purchases() {
return $this->hasMany('Purchase');
}
Purchase:
public function customer()
{
return $this->belongsTo('User');
}
Then in my controller when I call User::find(1)->purchases, I get class 'Purchase' not found and it's the same thing if I call Purchase::find(1)->customer, I get class 'User' not found. These models do exist as I can perform any other query with them.
Here is the schema for the purchases table:
Schema::create('purchases', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('package_id', 35);
$table->timestamps();
});
Here's the controller that I'm testing it in:
<?php namespace App\Http\Controllers;
use App\Purchase;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class HomeController extends Controller {
public function getHome()
{
return Purchase::find(1)->customer;
}
}
Note that I have included in the namespaces for these models. I need to know if I'm doing it right or if it's a bug with Illuminate/Database.
I needed to use the FQN of the model for this to work. Solved.
davidxd33 said:
I needed to use the FQN of the model for this to work. Solved.
Have an example of working code?
mottihoresh said:
davidxd33 said:
I needed to use the FQN of the model for this to work. Solved.
Have an example of working code?
I imagine he changed:
return $this->belongsTo('User');
to:
return $this->belongsTo('App\User');
At least that's what I had to do. Is this the proper way to do this?
Any word on this? Only way my models work is if I prepend the app name before the model name
return $this->belongsTo('AppName\Company');
I'm having the same problem.. I already have my namespace App; declared on top of the Model. I heard about using the composer dump-autoload will fix the problem, but it doesn't work for mine. Adding the extra namespace for every line of code works but it looks little bit ugly.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community