Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

Class Not Found again, this time when using "use"

I have a relationship in this form:

public function MyModel()
{
    return $this->hasOne('App\Models\MyModel');
}

But when I change it to:

use App\Models\MyModel;
public function MyModel()
{
    return $this->hasOne('MyModel');
}

I get the error of Class Not Found about MyModel.

What could cause this? I did refactor a typo in the project (renamed the Models folder name from Model to Models if that matters)

0 likes
8 replies
Sinnbeck's avatar

You need to use it correctly. Currently its a string, so php has no way of knowing that you mean a class name.

use App\Models\MyModel;
public function MyModel()
{
    return $this->hasOne(MyModel::class);
}
1 like
thinkverse's avatar

The string 'MyModel' won't work with use you need to use class constants, specifically the ::class one.

use App\Models\MyModel;
public function MyModel()
{
    return $this->hasOne(MyModel::class);
}
Sinnbeck's avatar

@Ligonsker No. this is just plain php. Nothing to do with laravel. What error are you getting?

1 like
Ligonsker's avatar

@Sinnbeck Class 'MyModel::class' not found(View:....)

It's being triggered by the blade template in the dd:

@dd(Auth::user()->MyModel)

But still, it works when using the previous way of using the class

(the relationship name is the same name as the model)

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@Ligonsker Did you wrap it in ' ' ? Can you show the code?

    return $this->hasOne('MyModel::class'); // wrong
    return $this->hasOne(MyModel::class); //correct
1 like

Please or to participate in this conversation.