1

Actually I don't have idea what is difference in both methods

Laravel Official documentation uses this below method for declaring relationship

class User extends Model
{
    public function phone()
    {
        return $this->hasOne('App\Phone'); // HERE (App\Phone) Parameter 
    }
}

and most of the tutorials and experts (even in Laracon's) uses this below method.

class User extends Model
{
    public function phone()
    {
        return $this->hasOne(Phone::class); // HERE (Phone::class) Parameter 
    }
}

In short what is difference in both, And which is convenient.

return $this->hasOne(Phone::class); // Method one
/// VS 
return $this->hasOne('App\Phone'); // Method Two
dipenparmar12
  • 3,042
  • 1
  • 29
  • 39
  • 2
    Does this answer your question? [What is ::class in PHP?](https://stackoverflow.com/questions/30770148/what-is-class-in-php). Also, you should always prefer the `::class` approach, as it's cleaner, and works well with IDEs' refactoring capabilities. – Jeto Apr 04 '20 at 12:08
  • 1
    Both are same, If you dump(Phone::class) you will see 'App\Phone' – Tharaka Dilshan Apr 04 '20 at 12:13

2 Answers2

1

They are both the same but Phone::class is new syntax
let's assume you want to move your Phone class to another folder you have to find every 'App\Phone' and rename it to New\Directory\Phone but when you use Phone::class you don't have to worry about that.

AH.Pooladvand
  • 1,944
  • 2
  • 12
  • 26
1

Since PHP 5.5 the class keyword is used for class name resolution. This means it returns the fully qualified ClassName. This is extremely useful when you have namespaces, because the namespace is part of the returned name.

Using the ::class keyword is the way to go. First because you write less, and second, using this your IDE can help you find the class faster.

But they're basically the same thing.

You can find more about that here

Piazzi
  • 2,490
  • 3
  • 11
  • 25