I want to know what User::class is called
A wholesome name to call this is class name resolution. It combines both the PHP resolution operator ::
and the class
keyword. lt is not a Laravel syntax sugar but a PHP one.
It, in all situations, returns the Fully qualified name of the class which is simply a string containing the absolute/relative path of the class file - depending on the namespace of the file/class where it is used.
From the PHP Manual
... use ClassName::class to get a fully qualified name of class ClassName
On the other hand, from the Laravel use-case you mentioned
public function user()
{
return $this->belongsTo(User::class);
}
The Laravel Eloquent method belongsTo()
and all similar methods specify that the parameter to be passed is a string. These methods resolve the string parameter to locate the model's class definition.
From the Laravel Docs
The first argument passed to the hasOne
method is the name of the related model.
Therefore using
return $this->belongsTo('\App\User');
OR
return $this->belongsTo(User::class);
are syntactically equivalent. That means that the method definition are exactly the same and there is no parameter type checking as both parameters are string.
So I like that Laravel "just knows" where the model is when you use that syntax sugar.
Yeah, it just knows. But it is really straight forward. It uses the string parameter of the Eloquent method (now we know that regardless of the syntax, it is a String) and the provided Namespace of the current class to locate the model definition.
For instance this class definition
<?php
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
is equivalent to
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne(Phone::class);
}
}
and also equivalent to
<?php
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne(App\Phone::class);
}
}
You will notice that the first and third examples do not need the namespace
directive because they are using the Absolute path names.