TheUnreal
TheUnreal

Reputation: 24492

Laravel Method [hasMany] does not exist

I have 2 controllers and models:

  1. User Controller & Model
  2. Hero Controller & Model

Each user can have unlimited heroes - it means that the relationship between them is one to many.

In my UserController I created the following method:

/**
     * Get the heroes of the user.
     */
    public function heroes()
    {
        return $this->hasMany(Hero::Class);
    }

while in my HeroController I created this method:

/**
 * Get the user that owns the hero.
 */
public function user()
{
    return $this->belongsTo(User::class)
}

Added this to my routes file:

Route::get('userHeroes', 'UserController@heroes');

and it returns this error:

{"error":{"message":"Method [hasMany] does not exist.","status_code":500}}

What could have gone wrong.. ?

Upvotes: 1

Views: 3749

Answers (3)

Vivek Pandey
Vivek Pandey

Reputation: 406

hasMany and belongsTo methods are eloquent class methods. And we inherit eloquent in our model so that we can use the eloquent methods functionality.

In order to use the relation, you have to define the relation method in respective model class and then you can call from controller.

Please refer the documentation Eloquent relationship documentation

Hope i have cleared your doubt.

Thanks

Upvotes: 0

aimme
aimme

Reputation: 6818

it must be declared in models, not in controllers, hasMany() is a method in eloquent models.

Upvotes: 1

Joel Hinz
Joel Hinz

Reputation: 25414

The controller is just a delegate between the request and the return data - you tell it that you want something, it figures out what you want, and then it calls the appropriate places to get something to return.

The hasMany() and belongsTo() methods, on the other hand, are logic specifically related to the Hero and User models, on the other hand.

What you need is to move the heroes() method to your User model, because a user can have many heroes. Also need the user() method to your Hero model, because a hero belongs to a user.

Then you put an action call in a controller. Let's say, for instance, that you have a UserController which has an getHeroes() method. That might look like this:

public function getHeroes() {
    $user = auth()->user();
    $heroes = $user->heroes;
    return $heroes;
}

And that will format it to JSON. Just an example.

But you might want to read a tutorial or two about this, since it's fairly basic stuff and it's good to get a good handle on early on. Please don't take that the wrong way - we're happy to help if you run into problems, I just think you might need a stronger foundation. The screencasts at Laracasts are highly recommended for this purpose.

Upvotes: 2

Related Questions