I'm using laravel 5.6.
I have 3 tables : players, games and game_player table.
Retrieving the game count of every player is easy with this in the index action of the PlayersController:
//Get game count of every player
$players = Player::withCount('games')->get();
Is there a way to retrieve the game count for the games when the player has won the game? (in the index action of the playerscontroller) I'm not sure how to do this. Can someone help?
games table migration
$table->integer('winner')->unsigned()->index();
$table->foreign('winner')->references('id')->on('players')->onDelete('cascade');
game_player table migration
table->integer('game_id')->unsigned()->nullable();
$table->foreign('game_id')->references('id')->on('games')->onDelete('cascade');
$table->integer('player_id')->unsigned()->nullable();
$table->foreign('player_id')->references('id')->on('players')->onDelete('cascade');
game model relation
public function players(){
return $this->belongsToMany('App\Player')->withTimestamps();
}
//this is for the winner of the game
public function player()
{
return $this->hasOne('App\Player');
}
player model relation
public function games(){
return $this->belongsToMany('App\Game')->withTimestamps();
}
//the game the player has won
public function game()
{
return $this->belongsTo('App\Game');
}
playerscontroller
public function index()
{
$players = Player::all();
//Get game count of every player
$players = Player::withCount('games')->get();
/*Load the view and pass the groups*/
return \View::make('players.index')->with('players', $players);
}
The result I want is to get played games (is working) and won games.
player > index blade
#foreach($players as $player)
<p>{{ $player->id }}</p>
<p>{{ $player->firstname }} {{ $player->lastname }}</p>
<ul>
<li>Played games: {{ $player->games_count }}</li>
<li>Won games: </li>
</ul>
#endforeach
update
I don't think we can see it as a duplicate of this question (Laravel using where clause on a withCount method) because I'm using a many to many relationship also.
If I use this code which isn't the correct one, because the 1 needs to be dynamic $id:
$players = Player::withCount('games')
->having('winner', '=', 1)
->get();
I get the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'winner' in 'having clause' (SQL: select players., (select count() from games inner join game_player on games.id = game_player.game_id where players.id = game_player.player_id) as games_count from players having winner = 1)
update 2
When I use this code:
controller
$players = Player::all();
//Get game count of every player
$players = Player::withCount('games')->get();
$wongames = Player::withCount(['games' => function($query) { $query->where('winner', '=', 5); }])->get();
//$players = Player::withCount('games')->where('winner', '=', 1);
/*Load the view and pass the groups*/
return \View::make('players.index')->with('players', $players)->with('wongames', $wongames);
blade index
#foreach($players as $player)
<p>{{ $player->id }}</p>
<p>{{ $player->firstname }} {{ $player->lastname }}</p>
<ul>
<li>Played games: {{ $player->games_count }}</li>
#foreach($wongames as $wongame)
<li>Won games: {{ $wongame->games_count }}</li>
#endforeach
</ul>
#endforeach
I get this (not what I exactly want, but getting there I think):
Since you define a foreign key on the games table, you have a one-to-many relationship between the Player and Game already. Try adding the following relation to your Player model:
// Player.php
public function won()
{
// must specify the foreign key because it is not the usual `_id` convention.
return $this->hasMany(Game::class, 'winner');
}
Then access it on each player like:
#foreach($players as $player)
{{ $player->won->count() }}
#endforeach
Rather than querying in the view file, you should ideally do the following in your controller:
public function index()
{
/*Load the view and pass the groups*/
return \View::make('players.index')->with('players', Player::with('won')->get());
}
Related
I have two different Models
App\Models\Team;
and
App\Models\Member;
Where my Team Model has this function
public function memberList()
{
return $this->hasMany('App\Models\Member');
}
and I'm using this code to show it on my blade
$team = Team::with('memberList')->get();
return view('front.pages.custom-pages-index', compact('team'));
here's my columns for the tables
MemberTable
Team Table
Now I'm trying to access the compact data using this foreach
#if(count($team))
#foreach($team as $field)
//Name of Team
<h1>{{$field->name}}</h1>
//Member
....
#endforeach
#endif
This is the sample content of compact data when I tried to access the {{ $team }} on blade file
[{
"id":1,
"name":"Executive Team",
"created_at":"2020-05-26 04:38:27",
"updated_at":"2020-05-26 04:38:27",
"member_list":[{
"id":1,
"team_id":1,
"position":1,
"name":"Chris White, PH.D",
"member_position":"President, Founder and CEO",
...And other member per specific team
The problem is I want to fetch on blade the members per specific teams
UPDATE
When I tried at least to access the name inside of the member_list using foreach
$field->member_list->name
I'm getting an error like this
Trying to get property 'name' of non-object
Tried to var_dump($field->member_list)
Tried this #php dd($field->member_list); #endphp
Because member_list item of variable field is an array and "name" isn't a key of this array. You should use another loop for your member list inside of your main loop.
#if(count($team))
#foreach($team as $field)
//Name of Team
<h1>{{$field->name}}</h1>
//Member
#if(!empty($field->member_list) OR !is_null($field->memberlist))
#foreach($field->member_list as $member)
<h2>{{$member->name}}</h2>
#endforeach
#endif
#endforeach
#endif
In my Member.php (Model)
Added this
public function member()
{
return $this->belongsTo('App\Models\Team', 'id', 'team_id');
}
In my Team.php (Model)
public function memberList()
{
return $this->hasMany('App\Models\Member', 'team_id', 'id');
}
Controller
$team = Team::with('memberList')->get();
return view('front.pages.custom-pages-index', compact('team'));
Blade
#if(count($team) > 0)
#foreach($team as $field)
{{$field->name}}
#foreach($field->memberList as $member)
{{$member->image}}
#endforeach
#endforeach
#endif
Need to map first the Team and Member models using its Primary key and Foreign Keys
And call the json column memberList
How can i display the most recent single record in laravel using eloquent the solution i have shown below only shows the oldest record in the database not the most recent.
I have two tables a payments table and tenants table.
payments table has the following columns
id
amount
rent_from
rent_to
Payments table has a many to one relationship with the tenants table.
In my index page i wish to only display the latest payment per tenant (tenant_id)
In my controller i have
public function index() {
$payments = Payment::groupBy('tenant_id')->get();
return view('payments.index')->with('payments',$payments);
}
index.blade.php
#foreach ($payments as $post)
{{ $post->id }}
{{ $post->amount }}
{{ $post->rent_from }}
{{ $post->rent_to }}
{{ $post->tenant['name'] }}
#endforeach
This show the oldest record not the latest. How can i display the most recent payment record for each tenant - only one most recent payment record per tenant_id
you could make a new relation called 'lastPayment' by using 'hasOne' with orderByDesc to get the last payment ....
class Tenant extends Model
{
public function lastPayment()
{
return $this->hasOne(Payment::class,'tenant_id')->orderByDesc('payments.id');
}
}
public function index()
{
$tenants= Tenant ::with('lastPayment')->get();
return view('payments.index')->with('tenants',$tenants);
}
The following gives me the output i needed. Is there a more eloquent way of expressing this function.
{
$payments = Payment::whereRaw('id IN (select MAX(id) FROM payments GROUP BY tenant_id)')->get();
return view('payments.index')->with('payments',$payments);}
latest() is a function that will order by with the column you provide in descending order.
public function index()
{
$payments = Payment::groupBy('tenant_id')->get()->latest('id');
return view('payments.index')->with('payments',$payments);
}
I have Stores and Medicines tables with many to many relationship. Storing and updating work fine with attach and sync. The table structure is like below. I want to retrieve value of extra column (expired).
store_id | medicine_id | expired
1 2 1
1 3 0
Also I need to count total medicines which expired like this
Both models have withPivot('expired') model relation.
Controller
public function show($id)
{
$medicine = Medicine::findOrFail($id);
$stores = $medicine->findorfail($id)->stores()->get();
return view ('medicines', compact('medicine', 'stores'));
}
View
I can list medicines with this
#foreach ($stores as $store)
{{ $store->value('name') }}
{!! $store->pivot->expired == 1 ?
'Expired' : 'Not-Expired' !!}
View
#endforeach
I tried to count Cities like this:
#foreach($stores as $store)
{{ ($store->pivot->expired==1) }}
#endforeach
It gives 1 1. How can I count total cities with have expired Cetamols?
The following should work:
Sum on the relationship collection:
$stores->sum('pivot.expired');
Sum on the Query Builder:
Medicine::findOrFail($id)->stores()->sum('expired');
Also your controller code does not make much sense at the moment and could be simplified to this:
public function show($id)
{
$medicine = Medicine::findOrFail($id);
$stores = $medicine->stores;
return view('medicines', compact('medicine', 'stores'));
}
I removed the second call to findOrFail() and removed the get() since it is unnecessary.
I have two database table
1. patient
--id
--name
2. report
--id
--description
and pivot talbe
patient_report
--id
--report_id
--patient_id
My Patient Model
class Patient extends Model
{
public function reports()
{
return $this->belongsToMany('App\Report' , 'patient_reports');
}
}
My Report Model
class Report extends Model
{
public function patients()
{
return $this->belongsToMany('App\Patient' , 'patient_reports');
}
}
My ReportControlller
public function viewList($reportFloor = null)
{
$report = Report::orderBy('created_at' , 'desc')->paginate(50);
return view('admin.report_list' , ['reports' => $report]);
}
Database : patients table have report_id column and reports table have patient_id column
N.B : I want to find the patient name who has a report. And i am using the laravel dynamic properties like that ---
And finally my blade
#foreach ($reports as $report)
{{ $report->patients->name }}
#endforeach
But it provides an error like that
Try this:
#foreach ($reports->patients as $patient)
{{ $patient->name }}
#endforeach
As the error implies, you're attempting to access the name attribute on a collection. To fix you should change:
#foreach ($reports as $report)
{{ $report->patients->name }}
#endforeach
to:
#foreach ($reports as $report)
#foreach ($report->patients as $patient)
{{ $patient->name }}
#endforeach
#endforeach
In your controller, i would first find the patients and afterwards get their reports.
$patients = Patient::with('reports')->get();
And then in the view i would do:
//This will first get all the patients
#foreach ($patients as $patient)
// This will get each of patients relational reports
#foreach ($patient->reports as $report)
{{ $report->name }}
#endforeach
#endforeach
I'm using Laravel to query users that have a score ( row in eventscore table )
And i want to return all the users that have scores for the event with an ID of 3
Is it possible to only return the score of every user, found in the pivot table ( see results below )
This is the code i'm using
$persons = Person::whereHas('eventscore', function($q) {
$q->where('id', 3);
})->with('eventscore')->get();
return $persons;
Thank you!
Try this:
// Person model
// accessor for easy fetching the score from the pivot model
public function getScoreAttribute()
{
return ($this->pivot && $this->pivot->score)
? $this->pivot->score
: null;
}
// example usage for the event's page (I assume participants is the relation)
$event = Event::with('participants')->find(3);
// somewhere in the view template
#foreach ($event->participants as $participant)
{{ $participant->name }} - score: {{ $participant->score }}
#endforeach