I have a charity_donations table which holds a charity_id, amount donated for that charity, among other fields. This is how it looks.
What I need to do is I need to groupBy each charity ID, then count how much money was donated for that particular charity. And most importantly, I need to display that in a view.
Some thing like this:
Charity ID | Total
1 | $1,200
....
I have tried this,
$displayPerCharity = CharityDonation::select(DB::Raw('charity_id, COUNT(*) as count'))->groupBy('charity_id')->get();
dd($displayPerCharity);
That counts the charity IDs, then gives me the total for each charity. But I need total amount for each charity, then display in view.
Got it!
$displayPerCharity = DB::table('charity_donations')
->select(DB::raw('SUM(amount) as charity_amount, charity_id'))
->groupBy('charity_id')
->orderBy('charity_amount', 'desc')
->get();
Then in view:
#foreach ($displayPerCharity as $group)
<h1> Charity ID {{ $group->charity_id }} received {{ $group->charity_amount }}</h1>
#endforeach
Well how you display it is entirely up to how you want it to look.
If you're just stuck on how to get each charity ID and amount out, then you can just do this with a foreach loop.
Here's an example using a Bootstrap responsive table. This assumes that after you have run your query you have passed it on to the view as a variable called $displayPerCharity.
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Charity ID</th>
<th>Amount ($)</th>
</tr>
</thead>
<tbody>
#foreach($displayPerCharity as $display)
<tr>
<td>{{ $display->charity_id }}</td>
<td>{{ $display->charity_amount }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
Related
In index.blade.php, I wrote these codes to show users who have roles
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Roles</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->roles }}</td>
<td>Show</td>
</tr>
#endforeach
</tbody>
And I wrote these codes in UserController,
$userId = \DB::table('role_user')->get()->pluck('user_id');
$users = User::find($userId);
return view('admin.index', compact('users'));
And I got these in the website:
[{"id":1,"name":"User Administrator","description":null,"created_at":"2021-11-23 03:06:49","updated_at":"2021-11-23 03:06:49","pivot":{"user_id":1,"role_id":1}}]
[{"id":2,"name":"Moderator","description":null,"created_at":"2021-11-23 03:06:49","updated_at":"2021-11-23 03:06:49","pivot":{"user_id":2,"role_id":2}}]
How can I only display the names in the table role column?
When calling user->roles, you're most likely calling towards a relation on your User model. This means that you're returning a collection. If you place a collection in curly braces in blade ({{ $user->roles }}), Laravel automatically calls toArray() on each model, and a json_encode on the result, which results in the JSON strings you end up seeing.
You only want the names, however, so it'd be better to grab those values and convert them to a string. An option of doing so is by plucking the name, and imploding the result:
implode(', ', $user->roles()->pluck('name')->toArray());
You have to call toArray() on the pluck() result, else you'll have a collection instead of an array, which implode does not work with.
If the user is logged in and his role is to be displayed, you can use this in your blade:
{{ Auth::user()->roles->pluck('name') }}
Or you would like to display the rools of another user, then you can do it as follows:
// in Controller fetch the user:
$user = User::find(42);
// in your Blade:
{{ $user->roles->pluck('name') }}
In this context, you have a number of methods that you can use:
roles
hasRole
hasAnyRole
hasAllRoles
getRoleNames
I am trying to show the table like below image
And i write the logic for this table creation is below
#foreach($users as $key => $user)
<tr>
<td>{{$key+1}}</td>
<td>{{$user->name}}</td>
<td rowspan="{{count($users->where('area',$user->area))}}">
{{$user->userarea->name}}</td>
<td rowspan="{{count($user->candidate->election->candidates)}}">{{$user->candidate->election->name}}</td>
</tr>
#endforeach
</tbody>
But this code produce me the following code like this
Here The Election and Candidate has one to many relationships and candidate and user has one one to one relationshipHelp me achieve my expected results.
You could keep track of which elections/area's have been rendered already. This could be done by creating an array containing a reference to these objects. Then in the template just add an if statement checking whether an election/area has been rendered:
<?php $renderedElections = []; ?>
<?php $renderedAreas = []; ?>
#foreach($users as $key => $user)
<tr>
<td>{{$key+1}}</td>
<td>{{$user->name}}</td>
#if (!in_array($user->userarea->name, $renderedAreas))
<?php $renderedElections[] = $user->userarea->name ?>
<td rowspan="{{count($user->userarea->name)}}">
{{$user->userarea->name}}
</td>
#endif
#if (!in_array($user->candidate->election->name, $renderedElections))
<?php $renderedElections[] = $user->candidate->election->name ?>
<td rowspan="{{count($user->candidate->election->candidates)}}">
{{$user->candidate->election->name}}
</td>
#endif
</tr>
This is not the best solution, but its simple and easy. For this to work, the users must be sorted perfectly by election and area.
This code is untested but should theorethically work. I tryied to gather informations about your model relationships from the code you posted, but it might need some tweaking with the model names and relations.
The following code basically fetches all the users each with their area, candidate and candidate.election relationships, then group users by 'election name' (first criteria), then 'area name' (second criteria).
The resulting array will be something like this:
// $elections will be:
// [
// 'Presidential' => [
// 'Dhaka-5' => [ candidates for that area in that election type ],
// 'Dhaka-1' => [ candidates for that area in that election type ],
// ...
// ],
// ...
// ]
In your controller do:
$elections = User::with('area', 'candidate.election')->get()->groupBy(function ($user) {
return $user->candidate->election->name;
}, function ($user) {
return $user->area->name;
});
// then pass $elections to the view...
Then in your view:
<table>
#php ($i = 1)
#foreach ($elections as $election => $areas)
#foreach ($areas as $area => $candidates)
#php ($areaLoop = $loop)
#foreach ($candidates as $user)
<tr>
<td>{{ $i++ }}</td>
<td>{{ $user->name }}</td>
#if ($loop->first)
<td rowspan="{{ $candidates->count() }}">{{ $area }}</td>
#endif
#if ($areaLoop->first)
<td rowspan="{{ $areas->sum(function ($area) { return $area->count(); }); }}">{{ $election }}</td>
#endif
</tr>
#endforeach
#endforeach
#endforeach
</table>
Note that $candidates->count() will be the number of candidates for that particular election area of the current election type. $areas->sum(...) will sum the number of candidates for each area to get the total count of candidates in that election type.
If you need further explaination or something doesn't work, just let me know. All the documentation about the collection functions I used is available here.
Hi i want do somethink like that: Page where user can look popularity rented cars.
I almost do this but i get some problems and i dont know how figure it.
I made relationship many-to-many and its working great.
View:
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Name Car</th>
<th>Popularity</th>
</tr>
</thead>
<tbody>
<?php $i = 1;?>
#foreach($cars as $car)
#foreach($car->rentcar as $rentcar)
<tr>
<td>{{ $i++ }}</td>
<td>{{$rentcar->name}}</td>
#foreach($car_pops as $car_pop)
<td>
#if($car_pop->total == '1')
<span class="glyphicon glyphicon-star"></span>
#elseif($car_pop->total == '2')
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
#endif
</td>
#endforeach
</tr>
#endforeach
#endforeach
</tbody>
</table>
Controller:
public function popularityCar()
{
$cars = User::with('rentcar')->get();
$car_pops = DB::table('rent_car')
->select('car_id', DB::raw('count(*) as total'))
->groupBy('car_id')
->get();
return view('user.popularityCar', ['cars' => $cars, 'car_pops' => $car_pops]);
}
in pivot table user can rent more then one time car with thats same name and i want display only one name car i mind i got audi and user rent it and second user rent it too but on other date so i want display only one time car audi and display popularity using bootstrap icon. and its almost working but showing more cars with thats same name so i trying groupBy like with checking popularity car but i got problem and i dont know how use it.
Model User:
public function rentcar()
{
return $this->belongsToMany(Cars::class, 'rent_car', 'user_id', 'car_id')->withTimestamps()->withPivot('start', 'end');
}
Model Cars:
public function caruser()
{
return $this->belongsToMany(User::class, 'rent_car', 'car_id', 'user_id');
}
So maybe is easy way to make query mysql with i can get car name and go to pivot table to get total car_id.
I am using Laravel 5.2.
My question is:
Can variable be classified in view?
For example:
There is a controller ,it can get all of the articles belonging to the current user, like this:
public function index()
{
$user=\Auth::user();
$articles = $user->articles;
return view('user.dashboard.index', compact('articles'));
}
In view,these codes below can show the articles,like this:
<div class="card">
<div class="card-header">
Articles
</div>
#if ($articles!=null)
<table class="table table-sm">
<thead>
<tr>
<th>title</th>
<th>created time</th>
<th>status</th>
</tr>
</thead>
<tbody>
#foreach ($articles as $article)
<tr>
<td>{{$article->title}}</td>
<td>{{$article->created_at}}</td>
<td>{{$article->status}}</td>
</tr>
#endforeach
</tbody>
</table>
#else
<p>Nothing</p>
#endif
</div>
These articles can be classified into two types:
1、“published”,status is 1.
2、“unpublished”,status is 0.
Question:
I would want the published articles to be shown in a card(div class="card"), and, the unpublished articles to be shown in another card.
Can they be classified in view? Thus,it doesn't need to query twice.
Try to use collection method where()
#foreach ($articles->where('published', 1)->all() as $article)
Just change published and 1 to real ones.
Fellow programmers,
I got a roster application build in PHP with the framework : Laravel. And i have the following issue:
My application has : Users, Taskdate's, and TaskdateTime. Each user can get a TaskdateTime assigned to them. That TaskdateTime is a child of Taskdate. I want to populate a schedule where each user can see all their times. The schedule looks like this :
What i do in my application is : Fetch all users, Fetch all Taskdate's and according to the Taskdate's, fetch the TaskdateTime's for the right Taskdate. I do this in the following way :
$taskdates = Taskdate::with('users')->where_date($date)->get();
$employees = Usergroup::with(array('users', 'users.workdates'))->where('usergroup_title', '=', 'Employees')->first();
You can see that i fetch usergroups, with the relationship : Users and with the User->workdates relationship. Where the workdates returns the TaskdateTime objects as mentioned above.
Now in my view, i do this to populate it with data. And this seems like a lot of extra hassle and i think it could me much easier but i can't wrap my head around it. Anyway, this is the code :
<table id="plan" class="table table-bordered">
<thead>
<th></th>
#foreach($taskdates as $taskdate)
<th id="{{ $taskdate->id }}">{{ $taskdate->subject }}</th>
#endforeach
</thead>
<tbody>
#foreach($employees as $employee)
<tr id="{{ $employee->id }}">
<td>{{ $employee->name }}</td>
#foreach($taskdates as $taskdate)
<?php
$result = array_filter($employee->workdates, function($user) use ($taskdate){
return $user->id === $taskdate->id;
});
?>
#if( empty($result) )
<td></td>
#else
<td id="{{$result[key($result)]->pivot->id }}" style="{{ ($result[key($result)]->pivot->taskdate_isread) ? '' : 'font-weight:bold;'}}">
{{date('H:i', strtotime($result[key($result)]->pivot->taskdate_time))}}
</td>
#endif
#endforeach
</tr>
#endforeach
</tbody>
</table>
So i am filtering the whole workdates relationship of each user, if its hold the Taskdate id. And if it is empty, then don't echo anything.
The syntax of the HTML/PHP is in BLADE, so it might not seem correct PHP parsing, but it is.
Edit :
Question :
My code feels bloated. I don't think this is the most efficient way to achieve the result. What is your opinion on this? I like to be as efficient as possible.