Search code examples
phplaravellaravel-5.3

Not able to use a certain word for a function name in Laravel


I have this basic app that i am working on in Laravel. A user asks a query and other users can comment on it.

I have this relationship built in the Comment model-

class Comment extends Model
{
    public function query()
    {
        return $this->belongsTo(Query::class);
    }
}

When i run php artisan tinker and create a new instance like so-

$comment = new App\Comment

I get an error-

Cannot make static method Illuminate\Database\Eloquent\Model::query() non static in class App\Comment

The problem i figured was with the name of the function 'query'. Because if i change the name to anything else, it works. I don't get any error.

I found out that there is a function in lluminate\Database\Eloquent\Model with the name 'query' that has this code in it-

public static function query()
{
    return (new static)->newQuery();
}

So, am I not allowed to use the word 'query' to name the function in my model?


Solution

  • Method query() is used in Model. So, only rename your method to avoid bad behavior.