Search code examples
laravelmethodsroutesmodeleloquent-relationship

Putting brackets when calling methods from laravel model


My route looks like this:

    Route::get('/tags/post/{id}', function ($id){
    $post = Post::find($id);

    foreach ($post->tags as $tag) {
        return $tag;
    }
});

tags() methot in Post Model looks like this:

    public function tags() {
    return $this->morphToMany('App\Models\Tag', 'taggable');
}

In this configuration my code will work, but when i put brackets after tags method in web.php my code returns null:

    Route::get('/tags/post/{id}', function ($id){
    $post = Post::find($id);

    foreach ($post->tags() as $tag) {
        return $tag;
    }
});

I need to know when do I put brackets after calling methods name?


Solution

  • $post->tags is a Property, and is equivalent to the Method call $post->tags()->get(). $post->tags() allows you to do extra queries, like $post->tags()->where(...), then you finish it with a Closure, like ->get() or ->first() – Tim Lewis

    Yeah, in Laravel, specifically with Models, using or omitting () makes a huge difference. Laravel "magically" converts relationship Methods like public function tags() to Properties for shortcut access, with the equivalency noted above. If you're ever unsure, use dd(), dd($post->tags) should show you a Collection, while dd($post->tags()) should show you a Builder instance, etc. Happy coding! – Tim Lewis