Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
Laravel 5.8: $bal->balance is getting null

I want to get a value of balance column from a pivot table called user_wallet which goes like this:

enter image description here

So I wrote this at the Controller:

$bal = Wallet::with("users")->whereHas('users', function ($query) use ($wallet_id, $user_id) {
    $query->where('wallet_id', $wallet_id);
    $query->where('user_id', $user_id);
})->first();

But when I do dd($bal->balance), I get null!

So why is that? How can I get the balance value based on user_id and wallet_id properly?

Here is also the relationships between User model and Wallet model:

User.php

public function wallets()
{
    return $this->belongsToMany(Wallet::class, 'user_wallet', 'user_id', 'wallet_id')->withPivot('balance');
}

Wallet.php

public function users()
{
    return $this->belongsToMany(User::class, 'user_wallet', 'wallet_id', 'user_id');
}

I would really appreciate any idea or suggestion from you guys...

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Your query is supposed to be like below. Becuase the relation you're making is with users table not user_wallet.

$bal = Wallet::with("users")
    ->whereHas('users', function ($query) use ($user_id) {
        $query->where('id',$user_id);
    })
    ->where('id', $wallet_id)
    ->first();

You can make a simple query as well:

$bal = DB::table('user_wallet')
    ->where('wallet_id', $wallet_id)
    ->where('user_id', $user_id)
    ->first();

if (!empty($bal)) {
    $balance = $bal->balance;
}
over 4 years ago · Santiago Trujillo Relatório

0

Since it is a many to many relationship, for getting the pivot table you loop like below:

@foreach($bal as $key => $value)
    {{$value->pivot->balance}}
@endforeach

or if it is a single item then you can do like:

$user = $bal->users()->first();

$user->pivot->balance;

or

$user = $bal->users->first();

$user->pivot->balance;

if still need directly then, as suggested by @Dilip Hirapara answer.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda