renathy
renathy

Reputation: 5345

Laravel FatalErrorException in Model.php line 827: Class not found

I am very new to Laravel. I have tried to use one example in my code, but as a result I got an error - FatalErrorException in Model.php line 827: Class Category not found.

Afterwards I have modified one line of code and fixed an error. However, I actually do not understand the reason of error and how I fixed it.

This is my code (as a result when I'm trying to build query using category - I am getting error):

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Category;

class Translation extends Model
{
    protected $fillable = array('lang1', 'lang2', 'lang1_code', 'lang2_code', 'category_id', 'created_at', 'updated_at');

    public function category() {
        return $this->belongsTo('Category', 'category_id');
        //return $this->belongsTo('App\Category', 'category_id');
    }        
}

However, when I modify one line, I do not get above error:

old line (error): return $this->belongsTo('Category', 'category_id');

new line (no error): return $this->belongsTo('App\Category', 'category_id');

Upvotes: 4

Views: 3518

Answers (2)

Peter Kota
Peter Kota

Reputation: 8340

In the relation you must add the full path before PHP 5.5:

'App\Category'

Since PHP 5.5, the class keyword is also used for class name resolution. You can get a string containing the fully qualified name of the ClassName class by using ClassName::class. This is particularly useful with namespaced classes.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Category;

class Translation extends Model
{
    protected $fillable = array('lang1', 'lang2', 'lang1_code', 'lang2_code', 'category_id', 'created_at', 'updated_at');

    public function category() {
        return $this->belongsTo(Category::class, 'category_id');
    }        
}

Upvotes: 2

cre8
cre8

Reputation: 13562

All your Models are normally stored in the App folder.

So for a relation you need to pass the full path to your Model, like

App\Category

Upvotes: 2

Related Questions