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
Answers:
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') ->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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0