Posts

Showing posts with the label eloquent

Laravel nested foreach by 2 different Models

Laravel nested foreach by 2 different Models I tried this. problem is, How to foreach data from different Models? Trying to get property of non-object (View: C:wamp64wwwzainsurgaltresourcesviewschoicesindex.blade.php) Controller $duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get(); $choices = Choice::where('user_id',Auth::id())->pluck('question_number')->toArray(); return view('choices.index',compact('duplicates','choices')); View @foreach ($duplicates as $duplicate) <tr> <td style="text-align: center;">{{ $duplicate->topic->id }}</td> <td style="text-align: center;">{{ $duplicate->topic->title }}</td> <td style="text-align: center;">{{ $duplicate->total }}</td> <td style=...

Merging Eloquent result set

Merging Eloquent result set I have two eloquent outputs allowance Amount A 100 B 80 C 120 D 150 AND Deductions Amount X 50 Y 60 Z 70 and json appears as $allowance = [{"allname":"A","allamount":"100"},{"allname":"B","allamount":"80"},{"allname":"C","allamount":"120"},{"allname":"D","allamount":"150"}] $Deductions = [{"dedname":"X","dedamount":"50"},{"dedname":"Y","dedamount":"60"},{"dedname":"Z","dedamount":"70"}]. I want new json to be like $new = [{"allname":"A","allamount":"100","dedname":"X","dedamount":"50"},{"allname":"B","allamou...

Eloquent get by related table count

Eloquent get by related table count I created messenger for laravel. Now I wanna list all threads in which user is participating with a count of messages in each thread. I need the count to where clause because I want to show only these threads, in which are messages. where My current query: $threads = Participant::with('thread.messages') -> where('user_id', Auth::user() -> id) -> get(); $threads = Participant::with('thread.messages') -> where('user_id', Auth::user() -> id) -> get(); Participant: public function user() { return $this -> hasOne(User::class, 'id', 'user_id'); } public function thread() { return $this -> hasOne(Thread::class, 'id', 'thread_id'); } Thread: public function participants() { return $this -> hasMany(Participant::class, 'thread_id', 'id'); } function messages() { return $this -> hasMany(Message::class, 'thread_id', 'id')...