return $this->belongsTo(User::class);
vs
return $this->belongsTo(AppUser);
What is the difference between the above two statements?
Advertisement
Answer
Actually, your second example is not valid. It needs to be a string:
return $this->belongsTo('AppUser');
Assuming it’s a string, there’s no difference between the two variations.
PHP 5.5’s class resolution (::class
) returns the fully qualified name of the class ({Namespace}ClassName
). You’re using it in the first example. But in the second example, you are passing the class FQN (AppUser
) manually, without using class resolution.
The important note is that the class should be available in the context (with a use
statement, if not in the current namespace), before you can use the class resolution against it. But in the second approach, you don’t need to the class to be available, you just pass the FQN as a string.
For long class FQNs which are available in the context, you’d prefer to use class resolution instead of manually passing it.
use IlluminateDatabaseEloquentModel; echo Model::class; // Outputs: IlluminateDatabaseEloquentModel;