Laravel + Inertia + Vue Js -> cant accsess to hasMany attributes

im new to Laravel, Inertiy and Vue JS. I have to setup a project with them, which works really cool.

Now i have a problem. I have a few games and every game hasMany ads. If i get the Games with something like:

$games = Game::where(['id' => auth()->user()->current_team_id])->orderBy('created_at', 'DESC')->with('theAds')->get();

in Game.php:

     * @return HasMany
    public function theAds(): HasMany
        return $this->hasMany(TheAds::class);

in TheAds.php:

 * @return BelongsTo
public function game()
    return $this->belongsTo(Game::class);

Now, if i var_dump($games[x][‘theAds’]->count()) it dumps the corrrect count for each game. But if i use it in Game.vue like this:

<tr v-for="(game, i) in $" :key="">
    <td class="text-center">{{ }}</td>
    <td class="text-center">{{ game.theAds }}</td>

it throws an error, that game.theAds is undefined, but is set correctly.

Could please somone help me?

Greetings Mickey


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Yes, that’s because it is too late to try to get data from relationships in js. You should get this data before ‘eloquent models’ convert to JSON

$games = Game::where(['id' => auth()->user()->current_team_id])->orderBy('created_at', 'DESC')->with('theAds')
->map(function ($e) {
                $e->theAds = $e->theAds;
                return $e;

Or you can create ‘ResourceCollection’ that help convert ‘eloquent models collection’ to JSON and then you can be able to access related data

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x