Export laravel data table to CSV - laravel

I have data in the view like so
<div class="box-body table-responsive no-padding">
<div id="users-table-wrapper">
<table id="users_table" class="table table-hover table-striped">
<tbody>
<tr>
<th>#lang('app.soldto')</th>
<th>#lang('app.soldby')</th>
<th>#lang('app.network')</th>
<th>#lang('app.plan')</th>
<th>#lang('app.sales_date')</th>
</tr>
#if (count($sales))
#foreach ($sales as $sale)
<tr>
<td>{{ $sale->soldto ?: trans('app.n_a') }}</td>
<td>{{ $sale->first_name . ' ' . $sale->last_name }}</td>
<td>{{ $sale->name }}</td>
<td>{{ $sale->plan }}</td>
<td>{{ $sale->salesdate }}</td>
</tr>
#endforeach
#else
<tr>
<td colspan="6"><em>#lang('app.no_records_found')</em></td>
</tr>
#endif
</tbody>
</table>
{!! $sales->render() !!}
</div>
</div>
</div>
I use pagination to display 10 rows per page. Like below
I want to download all this data to CSV. Without running the db query again.

Datatable itself provide the buttons to export csv, xls ,pdf etc. Here is the code
$('#example').DataTable( {
dom: 'Bfrtlp',
buttons: ['csv','pdf']
} );
'#example' is the id of your table

You can use working code below:
public static function exportCsv()
{
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$rows = DB::select( DB::raw("select * from users
;") );
$rows = json_decode(json_encode((array) $rows), true);
//\Log::info('query'.print_r($rows,true));
ob_end_clean();
$out = fopen('php://output', 'w');
foreach($rows as $key=>$values)
{
$arr = [];
foreach ($values as $key=>$value) {
array_push($arr, $key);
}
$line = $arr;
fputcsv($out, $line);
break;
}
//fputcsv($out, array('Registration', 'Name', 'Checkin Time'));
foreach($rows as $lines)
{
$line = $lines;
fputcsv($out, $line);
}
die;
fclose($out);
}

Related

how to show 3 Array in one datatable

I am trying to show 3 Array in one datatable.
// Combine Month Name and Data Array
$incomedataforyear = array();
$test1 = array_combine($getmonths, $incomedata);
$test2 = array_combine($getmonths, $animalselldata);
$test3 = array_combine($getmonths, $otherselldata);
$collection = collect([$test1, $test2, $test3]);
// End of Combine Month Name and Data Array
I also tried to use Collection but dont have any knowledge how to use this.
datatable code
<table id="incometable" class="table m-0 table table-bordered table-hover table" data-order='[[ 0, "desc" ]]'>
<thead>
<tr>
<th>Month</th>
<th>Milk Sale Amount (Rs.)</th>
<th>Animal Sale Amount (Rs.)</th>
<th>Other Sale Amount (Rs.)</th>
</tr>
</thead>
<tbody>
#foreach ($expdataresults as $item )
<tr>
<td>00</td>
<td>00</td>
</tr>
#endforeach
</tbody>
</table>
Thanks in Advance
Formatting a bit different, you could use array_merge_recursive
$test1 = array_combine($getmonths, array_map(fn($i) => ['incomedata' => $i], $incomedata));
$test2 = array_combine($getmonths, array_map(fn($i) => ['animalselldata' => $i], $animalselldata);
$test3 = array_combine($getmonths, array_map(fn($i) => ['otherselldata' => $i], $otherselldata);
$collection = collect(array_merge_recursive($test1, $test2, $test3));
#foreach ($collection as $key => $value)
<tr>
<td>{{ $key }}</td>
<td>{{ $value['incomedata'] }}</td>
<td>{{ $value['animalselldata'] }}</td>
<td>{{ $value['otherselldata'] }}</td>
</tr>
#endforeach

Laravel year, sum, count, group by eloquent query

Can someone show me how I would build this query with eloquent, or is this required to be written with a DB:Raw query, or would it be best to be a raw sql query?
select `pay_week`,
year(`start_timestamp`) as year,
sum(`total_duration`) as 'duration',
count(`pay_week`) as 'entries'
from `time_clock`
group by year(`start_timestamp`),`pay_week`;
Any help to better understand would be greatly appreciated.
Thank you.
$entries = TimeClock::select(
'pay_week',
DB::raw('count(pay_week) as entries'),
DB::raw('YEAR(start_timestamp) as year'),
DB::raw('sum(total_duration) as duration')
)
->where('user_id', $user->record_id)
->sum('total_duration')
->groupBy('pay_week')
->get();
results in a
Call to a member function groupBy() on float
What I have now;
Blade;
<table class="table table-hover dataTable table-striped width-full" data-plugin="dataTable">
<thead>
<th>Pay Week</th>
<th>Date Range</th>
<th>Year</th>
<th>Total Hours</th>
<th>Gross Pay</th>
<th>Entries</th>
<th>Action</th>
</thead>
<tbody>
#foreach($entries as $group)
#foreach($group->entries as $entry)
#php
$week_start = (new DateTime())->setISODate(date("Y"),$entry->pay_week)->format("m/d");
$start = \Carbon\Carbon::createFromFormat("m/d", $week_start);
$end = $start->copy()->endOfWeek()->format('m/d');
$year = \Carbon\Carbon::parse($entry->start_timestamp)->format('Y');
#endphp
<tr>
<td>{{ $entry->pay_week }}</td>
<td>{{ $start->format('m/d') . ' - ' . $end }}</td>
<td>{{ $year }}</td>
<td>0</td>
<td>$ 0.00</td>
<td>0</td>
<td>[ Btn ]</td>
</tr>
#endforeach
#endforeach
</tbody>
</table>
This is what I have in the controller method.
$user = Auth::guard('user')->user();
$entries = TimeClock::select(
'pay_week',
'start_timestamp',
'total_duration'
)
->where('user_id', $user->record_id)
->get()
->groupBy('pay_week')
->map(function($entry) {
return (object)[
'count' => $entry->count(),
'duration' => $entry->sum('total_duration'),
//'year' => $entry->sum('start_timestamp')->year,
'entries' => $entry
];
});
return view('user.timeclock.reports.all', [
'entries' => $entries
]);
Given, that you set the cast in your model
class TimeClock extends Model
{
protected $cast = [
'start_timestamp' => 'datetime'
];
}
you can do the following:
$entries = TimeClock::select(
'pay_week',
'start_timestamp',
'total_duration'
)
->where('user_id', $user->record_id)
//->groupBy('pay_week')
->get()
->groupBy([ 'pay_week', function($entry) {
return $entry->start_timestamp->year
})
/*->map(function($entry) {
return (object)[
'count' => $entry->count(),
'duration' => $entry->sum('total_duration'),
'year' => $entry->start_timestamp->year,
'entries' => $entry
];
})*/;
You loop over it like this:
<table>
<thead>
<tr>
<th>Pay week</th>
<th>Date range</th>
<th>Year</th>
<th>Total hours</th>
</tr>
</thead>
<tbody>
#foreach($entries as $pay_week => $groups)
#foreach($groups as $year => $group)
<!--pay_week: {{ $pay_week }}<br />
count: {{ $group->count() }}<br />
duration: {{ $group->sum('total_duration') }}<br />
year: {{ $year }}<br />-->
<tr>
<td>{{ $pay_week }}</td>
<td></td>
<td>{{ $year }}</td>
<td>{{ $group->sum('total_duration') }}</td>
</tr>
#foreach($group as $entry)
#endforeach
#endforeach
#endforeach
</tbody>
</table>

Laravel - syntax error, unexpected ')', expecting '['

I am using Laravel 5.8 to create an App. When I wanted to display the view, it generated an error as shown below:
syntax error, unexpected ')', expecting '['
Controller
public function serviceOverview(Request $request)
{
$data['title'] = 'Subscription Overview';
$serviceoverviews = DB::table("service_package")
->join('services', 'services.id', '=', 'service_package.service_id')
->join('service_type', 'service_type.id', '=', 'services.service_type')
->select('service_package.title as service_id', 'service_package.title as package_name', DB::raw("DATE(service_package.created_at) as created_at"), 'service_package.price', 'service_package.days','services.name as service_name','service_type.name as service_type');
$render=[];
if(isset($request->package_name))
{
$serviceoverviews=$serviceoverviews->where('serviceoverviews','like','%'.$request->serviceoverviews.'%');
$render['package_name']=$request->package_name;
}
if(isset($request->service_id))
{
$serviceoverviews=$serviceoverviews->where('service_id',$request->service_id);
$render['service_id']=$request->service_id;
}
$serviceoverviews= $serviceoverviews->orderBy('created_at','DESC');
$serviceoverviews= $serviceoverviews->paginate(15);
$serviceoverviews= $serviceoverviews->appends($render);
$data['serviceoverviews'] = $serviceoverviews;
return view('report.serviceOverview',$data);
}
In the Controller, I tried to do some filtering. Also, I did raw query.
View
<div class="box box-primary">
<div class="box-header with-border">
#if(Session::has('flash_message'))
<div class="alert alert-success">
{{ Session::get('flash_message') }}
</div>
#endif
#if(count($detailsubscriptions))
<table class="table table-bordered table-hover table-striped table-condesed" id="commenter_info_table">
<caption></caption>
<thead>
<tr>
<td>#</td>
<td>Service</td>
<td>Package</td>
<td>Service Type</td>
<td>Date</td>
<td>Price</td>
<td>Days</td>
</tr>
</thead>
<tbody>
#foreach($serviceoverviews as $key => serviceoverview)
<tr>
<td>{{ ++$key }}</td>
<td>{{ serviceoverview->service_name }}</td>
<td>{{ $serviceoverview->package_name }}</td>
<td>{{ $serviceoverview->service_type }}</td>
<td>{{ serviceoverview->created_at }}</td>
<td>{{ $serviceoverview->price }}</td>
<td>{{ $serviceoverview->days }}</td>
</tr>
#endforeach
<tr>
<td colspan="8">
{{ $serviceoverview->links() }}
</td>
</tr>
</tbody>
</table>
#else
<div class="row text-center">
<h2>No Service Overview to show</h2>
</div>
#endif
</div>
</div>
I tried to check the code, but found nothing. How do I resolve this issue
You have missed a $ from the $serviceoverview variable in your blade #foreach. Change:
#foreach($serviceoverviews as $key => serviceoverview)
To
#foreach($serviceoverviews as $key => $serviceoverview)
Here is the full code updated with changes. Please refer to this
Controller.php
public function serviceOverview(Request $request)
{
$builder = DB::table("service_package")
->join('services', 'services.id', '=', 'service_package.service_id')
->join('service_type', 'service_type.id', '=', 'services.service_type')
->select('service_package.title as service_id', 'service_package.title as package_name', DB::raw("DATE(service_package.created_at) as created_at"), 'service_package.price', 'service_package.days','services.name as service_name','service_type.name as service_type');
if($request->filled('package_name'))) {
$builder = $builder->where('serviceoverviews','like','%'.$request->serviceoverviews.'%');
}
if(isset($request->service_id))
{
$builder=$builder->where('service_id',$request->service_id);
}
$serviceoverviews = $builder->orderBy('created_at','DESC')->paginate(15);
$data = [
'title' => 'Subscription Overview',
'serviceoverviews' => $serviceoverviews
];
return view('report.serviceOverview', $data);
}
Now change your view code like this.
view.blade.php
<table class="table table-bordered table-hover table-striped table-condesed" id="commenter_info_table">
<caption></caption>
<thead>
<tr>
<td>#</td>
<td>Service</td>
<td>Package</td>
<td>Service Type</td>
<td>Date</td>
<td>Price</td>
<td>Days</td>
</tr>
</thead>
<tbody>
#foreach($serviceoverviews as $key => $serviceoverview)
<tr>
<td>{{ ++$key }}</td>
<td>{{ $serviceoverview->service_name }}</td>
<td>{{ $serviceoverview->package_name }}</td>
<td>{{ $serviceoverview->service_type }}</td>
<td>{{ serviceoverview->created_at }}</td>
<td>{{ $serviceoverview->price }}</td>
<td>{{ $serviceoverview->days }}</td>
</tr>
#endforeach
<tr>
<td colspan="8">
{{ $serviceoverview->appends(\Request::all())->links() }}
</td>
</tr>
</tbody>
</table>
You are using serviceoverview in place of $serviceoverview in view file. That would be an issue.
You have made some typo and one logical error.
Change
#foreach($serviceoverviews as $key => serviceoverview) to #foreach($serviceoverviews as $key => $serviceoverview)
<td>{{ serviceoverview->service_name }}</td> to <td>{{ $serviceoverview->service_name }}</td>
You have put {{ $serviceoverview->links() }} out side of the foreach loop

Use button inside controller

I am trying to search users in a panel with ajax. But along with that, I also want to edit the selected user.
I have created the button inside the controller to achieve this but the button isn't working.
Here is my controller code:
public function searchTeacher(Request $request){
if($request->ajax()){
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('users')->where('name', $query)->get();
}else{
$data = DB::table('users')->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->teacherId.'</td>
<td>'.$row->subject.'</td>
<td> <button href={{route(update-teacher-view), '.$row->id.'}}> Edit</button> </td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
Here is the ajax for search method-
<script>
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
console.log(query)
$.ajax({
url:"{{ route('search-teacher') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query);
});
});
Here is my html-
<section class="panel">
<table class="table table-striped">
<thead class="team-list chat-list-side info border-less-list">
<th>Teacher Name</th>
<th>Email</th>
<th>Teacher Id</th>
<th>Subject</th>
</thead>
<tbody>
</tbody>
</table>
</section>
A solution will be appreciated.
Thanks in advance.
Maybe it's a wrong string interpolation? Should be like this:
<?php
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->teacherId.'</td>
<td>'.$row->subject.'</td>
<td> <button href='.route('update-teacher-view', $row->id).'> Edit</button> </td>
</tr>
';
Also instead of echo-ing, just return the value, it will be automatically converted to JSON response:
// echo json_encode($data); // Change this line to below
return $data;
Render the blade file with the data this is the best solution.
In controller
return View::make('ajaxFilter',compact('data'))->render();
On ajaxFilter.blade.php
<section class="panel">
<table class="table table-striped">
<thead class="team-list chat-list-side info border-less-list">
<th>Teacher Name</th>
<th>Email</th>
<th>Teacher Id</th>
<th>Subject</th>
</thead>
<tbody>
#if($data->count() > 0)
#foreach($data as $row)
<tr>
<td>{{ $row->name }}</td>
<td>{{ $row->email }}</td>
<td>{{ $row->teacherId }}</td>
<td>{{ $row->subject }}</td>
<td>
Edit //button design
</td>
</tr>
#endforeach
#else
No data Found
#endif
</tbody>
</table>
</section>
On ajax response, you can append HTML data something like that
$('#div_or_section_id').html(data);

Print indexed array value in view.blade.php in laravel5.2

I have one associative array $collection and one indexed array $gnd which I have passed from Controller to my view.blade.php in Laravel 5.2. I want to print the values of both the arrays in a single table. Here is my code,
<table class="responsive-table highlight centered">
<thead>
<tr>
<th data-field="id">Sl.no</th>
<th data-field="name">Unique </th>
<th>Name</th>
<th data-field="price">Description</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
{{-- */$j = 1;/* --}}
#foreach($collection as $key=>$value)
<tr>
<td>{{ $j }}</td>
<td>{{ $value->uid }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->desc }}</td>
<td>{{ $gnd[$j] }}</td>
{{-- */$j++;/* --}}
#endforeach
</tr>
</tbody>
</table>
For {{ $gnd[$j] }} I am getting the following error.
ErrorException in b7c1ab515a44988c31e1982a3ce014434e97ef2c.php line 30:
Undefined offset: 22 (View: /var/www/html/anudip/resources/views/plugins/entries/view.blade.php)
I am new in laravel. Please help me...
Function that passes the two arrays from Controller:
public function getDetails(){
$collection = DB::table('entry_transactions')
->leftJoin('entry_masters', 'entry_transactions.entry_id', '=', 'entry_masters.id')
->get(['entry_masters.id as uid','entry_masters.name as name','entry_masters.gender as gender','entry_transactions.entry_desc as desc']);
$gnd = array();
$len = sizeof($gnd);
$i = 0;
foreach ($collection as $key) {
if($key->gender == 0){
$gnd[$i] = "Male";
}
else {
$gnd[$i] = "Female";
}
$i++;
}
return view($this->url.'entries.view', compact('collection','gnd'));
}
The error you are getting because both array's size are not equal!
And why are you starting $j = 1? shouldn't be $j = 0, if both your arrays has the same size $j = 0 will fix your problem and change <td>{{ $j }}</td> to <td>{{ $j+1 }}</td>
Also, can you show us your controller function that is sending this two arrays?

Resources