简体   繁体   中英

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?

replace your code with it

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM