Sep 6, 2017
0
Level 3
Linking user_id to the user name in a different table and using Vue to show the results
I am trying to setup a site to show who can/can not attend events. I have 3 models, Users, Games, Rsvps
class User extends Authenticatable
{
/**
* Get all of rsvps for the user.
*/
public function rsvps()
{
return $this->belongsToMany(Game::class, 'rsvps', 'user_id', 'game_id');
}
}
class Game extends Model
{
public function rsvpd() {
return (bool) Rsvp::where('user_id', Auth::id())
->where('game_id', $this->id)
->first();
}
public function rsvps() {
return $this->hasMany(Rsvp::class);
}
}
class Rsvp extends Model
{
public function game()
{
return $this->belongsTo(Game::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Here are my migration tables:
Schema::create('games', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('location')->nullable();
$table->datetime('date')->nullable();
$table->timestamps();
});
Schema::create('rsvps', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('game_id')->unsigned();
$table->timestamps();
});
My GamesController has this index method:
public function index()
{
$games = Game::with('rsvps')->get();
return view('games.index', compact('games'));
}
I am using Vue as well to handle the Rsvp states, here is my Rsvp.vue file
<template>
<span>
<a href="#" v-if="isRsvpd" @click.prevent="unRsvp(game)">
<i class="fa fa-heart"></i>
</a>
<a href="#" v-else @click.prevent="rsvp(game)">
<i class="fa fa-heart-o"></i>
</a>
</span>
</template>
<script>
export default {
props: ['game', 'rsvpd'],
data: function() {
return {
isRsvpd: '',
}
},
mounted() {
this.isRsvpd = this.isRsvp ? true : false;
},
computed: {
isRsvp() {
return this.rsvpd;
},
},
methods: {
rsvp(game) {
axios.post('/rsvp/'+game)
.then(response => this.isRsvpd = true)
.catch(response => console.log(response.data));
},
unRsvp(game) {
axios.post('/unrsvp/'+game)
.then(response => this.isRsvpd = false)
.catch(response => console.log(response.data));
}
}
}
</script>
I want to display the name of the user who can attend a game in my view. Currently, I have something like this but I'm not sure how to show the name in the 2nd panel-body...
@forelse ($games as $game)
<div class="panel panel-default">
<div class="panel-heading">
{{ $game->location }}
</div>
<div class="panel-body">
{{ $game->date }}
</div>
<div class="panel-body">
<ul>
<li>
{{ -- need to show name here -- }}
</li>
</ul>
</div>
@if (Auth::check())
<div class="panel-footer">
<rsvp
:game={{ $game->id }}
:rsvpd={{ $game->rsvpd() ? 'true' : 'false' }}
></rsvp>
</div>
@endif
</div>
@empty
<p>No game created.</p>
@endforelse
If anyone could help point me in the right direction, I'd appreciate it.
Please or to participate in this conversation.