Search code examples
laravellaravel-5eloquentmodels

Class Not Found - Eloquent


i have these two models:

<?php namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model {

    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'is_active'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    public function customer_details()
    {
        return $this->hasOne('CustomerDetails', 'user_id');
    }

}

And:

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CustomerDetails extends Model {

    protected $table = 'customer_details';

    public function user()
    {
        return $this->belongsTo('User');
    }
}

Now i am trying to get all customers along with their user data from the database in my index() of my UserController():

/**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $users = User::with('customer_details')->get();

        return [
            'users' => $users
        ];
    }

But i keep getting this error:

Fatal Error Exception Class 'CustomerDetails' not found

I have no idea what i am doing wrong here.


Solution

  • Your class is namespaced and should therefore be referred to as App\Models\CustomerDetails, in the $this->hasOne(...) definition of customer_details of the App\Models\User model.