Skip to content
Advertisement

How to find data based on Many To Many relationship in Laravel 5.8

I have a Many To Many relationship between User Model & Wallet Model:

Wallet.php:

public function users()
    {
        return $this->belongsToMany(User::class);
    }

And User.php:

public function wallets()
    {
        return $this->belongsToMany(Wallet::class);
    }

And I have these three tables related to Wallets:

Table wallets:

public function up()
    {
        Schema::create('wallets', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('name')->unique();
            $table->tinyInteger('is_active');
            $table->tinyInteger('is_cachable');
            $table->timestamps();
        });
    }

Table user_wallet:

public function up()
    {
        Schema::create('user_wallet', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('usr_id')->on('users');
            $table->unsignedBigInteger('wallet_id');
            $table->foreign('wallet_id')->references('id')->on('wallets');
            $table->integer('balance');
            $table->timestamps();
        });
    }

And table user_wallet_transactions:

public function up()
    {
        Schema::create('user_wallet_transactions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('usr_id')->on('users');
            $table->unsignedBigInteger('wallet_id');
            $table->foreign('wallet_id')->references('id')->on('wallets');
            $table->string('amount');
            $table->string('description');
            $table->timestamps();
        });
    }

Now I need to show wallets of a single user. So at the users.index Blade, I added this:

<a href="{{ route('user.wallet', $user->usr_id) }}" class="fa fa-wallet text-dark"></a>

And send the user data to Controller like this:

public function index(User $user)
    {
        // retrieve user_wallet information
        return view('admin.wallets.user.index', compact(['user']));
    }

But I don’t know how to retrieve user_wallet information at this Method.

So how to get data from user_wallet in this situation.

I would really appreciate any idea or suggestion from you guys about this…

Thanks in advance.

Advertisement

Answer

One way is accept param as $id

public function index($id)

then

User::with('wallets')->has('wallets')->find($id);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement