0

I'm using Eloquent ORM in Laravel. There is 2 model, User and Trans. User hasMany Trans, and Trans belongsTo User. The problem is when I'm using query where, it doesn't work.

I tried using ->get() in the last code, it still doesn't work. I tried using ->all() in the last code it still doesn't work. I tried whereIn, it still doesn't work.

User Model

public function trans()
{
    return $this->hasMany('App\Trans', 'user_id');
}

Trans Model

public function user ()
{
    return $this->belongsTo('App\User','user_id');
}

Controller

$trans = Auth::user()->trans->where('date', $date);

I want the output is based on query where the date is based on user input, when I delete ->where , it works and the output like this.

Collection {#797 ▼
  #items: array:13 [▼
    0 => Trans {#783 ▶}
    1 => Trans {#784 ▶}
    2 => Trans {#785 ▶}
    3 => Trans {#786 ▶}
  ]
}
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
Ray Coder
  • 1,022
  • 3
  • 15
  • 30
  • add `user` and `trans` model in question – Jignesh Joisar Jan 05 '19 at 08:50
  • 1
    used like that `Auth::user()->trans()->where('date', $date);` add `()` after trans – Jignesh Joisar Jan 05 '19 at 08:52
  • when i add () it give me weird array : HasMany {#803 ▼ #foreignKey: "transactions.user_id" #localKey: "id" #query: Builder {#802 ▼ #query: Builder {#801 ▶} #model: Transaction {#799 ▶} #eagerLoad: [] #localMacros: [] #onDelete: null #passthru: array:13 [▶] #scopes: [] #removedScopes: [] } #parent: User {#533 ▶} #related: Transaction {#799 ▶} } – Ray Coder Jan 05 '19 at 08:54
  • 1
    `Auth::user()->trans()->where('date', $date)->get();` and add get() method to get row data – Jignesh Joisar Jan 05 '19 at 09:01

1 Answers1

1

try to change like that

Auth::user()->trans->where('date', $date);

to

Auth::user()->trans()->where('date', $date)->get();

note : if you want to get only property then u get property without pointer but if you want to used another method then must used(add) pointer(->).

Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57