Home > Net >  Track multiple booleans with laravel's many to many relationship
Track multiple booleans with laravel's many to many relationship

Time:07-07

My migration code for relation table:

Schema::create('users_games', function (Blueprint $table) {
        $table->bigInteger('user_id')->unsigned();
        $table->index('user_id');
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

        $table->bigInteger('game_id')->unsigned();
        $table->index('game_id');
        $table->foreign('game_id')
            ->references('id')
            ->on('games')
            ->onDelete('cascade');

        $table->boolean('liked')->default(false);
        $table->boolean('played')->default(false);
        $table->boolean('wishlisted')->default(false);

        // composite primary key
        $table->primary(['user_id', 'game_id']);
    });

basically a user can mark a game like, played or add to wishlist. I want to track all those actions in the same table.

I want to represent the same in Elloquent Model for users and games, however I dont know how to. can anyone tell me how these properties inside respective models should look like please?

CodePudding user response:

in your User Model:

<?php
namespace App\Models;
class User extends Model
{
    public function games()
    {
        return $this->hasMany(Game::class);
    }
}

in your Game model:

<?php
namespace App\Models;
class Game extends Model
{
    public function user()
    {
        return $this->belongsToMany(User::class);
    }
}

then you can get the value of played property from the first game in the Eloquent like this:

$user = auth->user()
$user->games->first()->liked
  • Related