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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With