Volatil3
Volatil3

Reputation: 14998

Laravel: Model Class not found in relationships

Using Relationships first time and having issue to understand it.

I have a Student Class and a Course Model Class. A student can take many courses. In Student Model I do this:

public function course()
    {        
        return $this->belongsTo('Course');
    }

and in controller when I do this: .$student->course()->course_title it gives an error:

FatalThrowableError in Model.php line 779:
Class 'Course' not found

What am I doing wrong?

Upvotes: 0

Views: 1902

Answers (3)

yajuve
yajuve

Reputation: 11

I had the same problem and i solved it by adding a name space in the top of my model

for your case,

use \App\Course ; // Your name space of your class in relation

Hope this help others

NB : I used Laravel 5.0

Upvotes: 0

idelara
idelara

Reputation: 1816

Make sure your namespace in your Course class matches 'App\Models'. You might be trying to access an "empty" namespace.

Namespaces are declared at the top of your class file. So for example:

Course.php:

namespace App\Models;

use Illuminate\Http\Request;
...


class Course extends Model { ... }

OtherClass.php

namespace App\Models;

use Illuminate\Http\Request;
...


class OtherClass extends Model { 

...

    public function course()
    {
        return $this->belongsTo('App\Models\Course')
    }

}

Please note that the namespace declared at the top of Course.php matches the path provided to the relationship method (return) belongsTo(). You can also provide Course::class to the belongsTo method, but you need to import aka use the class in your php class.

I hope this helps!

Upvotes: 0

Imran
Imran

Reputation: 41

replace your code with it

public function course()
{
    return $this->belongsTo(Course::class);
}

Upvotes: 2

Related Questions