Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, using model method as property

I am new to Laravel and playing around with it. Sorry if this is a silly question. I just could not figure out how eloquent relationships work. For example:

// we have posts and comments related to them
class Post extends Model
{
    public function comments(){
        return $this->hasMany(Comment::class);
    }
}

Now we can do this to get comments of the specified post:

$comments = $post->comments;

The first question is: how can be this possible. Where in Laravel the name of the method declared as a property.

The second question is: how can I use Comment class without calling it on the head of the file with 'use' statement. (use App\Comments)

Thanks.

like image 476
Melih Polat Avatar asked Dec 06 '25 00:12

Melih Polat


1 Answers

Answer to Question 1: Laravel uses the magic __get() method to access the method as property which internally calls many functions to get the relationship. You can check the code here

Answer to Question 2: You can pass the class path as string as a parameter to the relationship like

return $this->hasMany('App\Comments');
like image 101
linktoahref Avatar answered Dec 07 '25 15:12

linktoahref