Model is not found. Bug in Laravel Framework?

80 Views Asked by At

My Model is like this

class redModel extends Model {

    public $table = 'tbl50red';
    public $primaryKey = 'RedID';
    public $timestamps = true;

}

and here is another model

class AddOnModel extends Model {

    public $table = 'tbladdon';
    public $primaryKey = 'AddOnID';
    public $timestamps = true;

    public function AppRed() {
        return $this->hasMany("\App\Models\AddOn\Red\redModel", "AddOnID", "AddOnID");
    }
}

In the controller when i run this:

$AddOns = AddOnModel
    ::with(array("AppRed" => function($query) use($StartDate, $EndDate) {
        return $query->whereBetween("EarningDate", array($StartDate, $EndDate));
    }))
    ->get();

I get an exception :

Class '\App\Models\AddOn\Red edModel' not found

Am I missing something?

4

There are 4 best solutions below

0
On BEST ANSWER

This is not a bug in Laravel. Please read the PSR-1 Basic Coding Standard which will enable you to easily avoid this error in the future. Namely, this is the part you are violating:

Class names MUST be declared in StudlyCaps.

0
On

Change "\App\Models\AddOn\Red\redModel" to:

"\App\Models\AddOn\Red\\redModel"

i.e. the extra \ will escape the \r. \r is a control character, which is why you're getting an issue.

0
On

When I open below file:

\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php

and checked this function

public function hasMany($related, $foreignKey = null, $localKey = null)
{
    $foreignKey = $foreignKey ?: $this->getForeignKey();
    $instance = new $related;

    $localKey = $localKey ?: $this->getKeyName();

    return new HasMany($instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey);
}

I saw I was not able to instantiate the model because model name was starting with r . lol

and i was pulling my hair since morning and another coincident was that it was like this \r so it was missing the model name and I think replacing \r with blank space and due to that the url was becoming like this

\App\Models\AddOn\Red edModel

and actual was this

\App\Models\AddOn\Red\redModel

I think it's a bug in Laravel framework.

0
On

You may try the given way...

use Illuminate\Database\Eloquent\Model;

class Application extends Model
{
    public function AppRed()
    {
        return $this->hasMany(redModel::class);
    }
}