0

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 $page.props.games" :key="game.id">
    <td class="text-center">{{ game.name }}</td>
    <td class="text-center">{{ game.theAds }}</td>
</tr>

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

Could please somone help me?

Greetings Mickey

1 Answer 1

2

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')
->get()
->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 https://laravel.com/docs/8.x/eloquent-resources#resource-collections

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.