I'm currently trying to learn how databases work in Laravel and encountered a problem and don't know how to fix it or what will be a good solution. Where getting and displaying sum() of column by distinct() id column of one table with other details from the unique id in Laravel.
The data inside my databases are
name | phone | address | ordered | |
---|---|---|---|---|
John | [email protected] | 55982911 | St. Louis | 2 |
John | [email protected] | 55982911 | St. Louis | 1 |
Mike | [email protected] | 55876988 | St. Thomas | 2 |
Mike | [email protected] | 55876988 | St. Thomas | 3 |
And how I wanted it to be displayed
name | phone | address | ordered | |
---|---|---|---|---|
John | [email protected] | 55982911 | St. Louis | 3 |
Mike | [email protected] | 55876988 | St. Thomas | 5 |
The code inside my blade
<table bgcolor="grey" border="2px">
<tr>
<th style="padding: 30px">Name</th>
<th style="padding: 30px">Email</th>
<th style="padding: 30px">Phone</th>
<th style="padding: 30px">Address</th>
<th style="padding: 30px">Ordered</th>
</tr>
@foreach($data as $data)
<tr align="center">
<td>{{$data->name}}</td>
<td>{{$data->email}}</td>
<td>{{$data->phone}}</td>
<td>{{$data->address}}</td>
<td>{{$data->ordered}}</td>
</tr>
@endforeach
</table>
And the code I'm trying to configure
public function viewreservation()
{
if(Auth::id()){
$data=reservation::select('name', 'email', 'phone', 'address')
->distinct()
->get();
return view("viewreservation",compact("data"));
}
Can adding a sum() function be done together with displaying the distinct values I am displaying or should I separate it? if possible, how should I do it?
CodePudding user response:
You can use groupBy()
in Laravel.
$data = reservation::select(array(
'name', 'email', 'phone', 'address'
))->groupBy(YOUR COLUMN NAME)->get();
Before you use groupBy()
make sure you have set strict mode false in the database configuration.
in /config/database.php
'mysql' => [
// other config values
'strict' => false,
// other config values
],
Hope that will helps you to solve your query!!!
Happy Coding!!