export data from current search into excel in Laravel? - excel

After search the search result is displayed in the screen. That content I must download as excel.
Controller.php
public function searchList(Request $request)
{
$fleet_issues = FleetIssue::all();
$list = FleetIssue::orderBy('check_at', 'desc');
$directory = FleetManagementHelper :: getFleetIssueImageDirectory();
$fleet_issue_type = FleetIssueType::all();
$vehicle_class = VehicleClass::orderBy('id', 'asc')->get();
$location= Location::orderBy('id', 'asc')->get();
if( $request->plate_number){
$list = $list->where('plate_number', $request->plate_number );
}
if( $request->branch){
$list = $location->where('id', $request->branch );
}
if( $request->nric){
$list = $list->where('nric',$request->nric);
}
if( $request->fleet_issue_type_id){
$list = $list->where('fleet_issue_type_id',$request->fleet_issue_type_id);
}
$list = $list->paginate(20);
view('pages.control_panel.view_issues',compact('list','fleet_issues','directory','fleet_issue_type','vehicle_class','location'));
}
Below is to download the excel file from the Export.php
public function downloadExcel()
{
return Excel::download(new Export,'List.xlsx');
}
Below is the Export.php..How can i filter search here??
Export.php
Use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
class Export implements FromView,ShouldAutoSize,WithHeadings, WithEvents
{
public function headings(): array
{
return [
'Reservation Number', 'NRIC/Passport', 'Vehicle Model','Branch','Date of Checking','Issues'
];
}
public function view() : View
{
$vehicle_class = VehicleClass::orderBy('id', 'asc')->get();
$location= Location::orderBy('id', 'asc')->get();
$fleet_issue_type = FleetIssueType::orderBy('id', 'asc')->get();
$list = FleetIssue::orderBy('check_at', 'desc')->paginate(20);
$directory = FleetManagementHelper :: getFleetIssueImageDirectory();
if( $this->vehicle_model){
$list = $list->where('vehicle_model', $this->vehicle_model);
}
return view('pages.control_panel.fleet_management.fleet_issues.list_fleet_issues',compact('vehicle_class','location','fleet_issue_type','list','directory'));
}
How can i export my result from search to excel?How i can filter the searchlist in Export??How to passing current request variable in export like doing in the controller?

Related

Export images with Laravel-Excel

my Code Here is Exporting Images For Products Table but it exported in this format https://prnt.sc/109zsm6 i think image not setting for column value or not overriding
in column there is image and text from $product->image how should print image in right way
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
//Freeze frist row
$event->sheet->freezePane('A2', 'A2');
$products = Product::limit(10)->get();
//Set row height
for ($i = 0; $i < count($products); $i++) //iterate based on row count
{
$event->sheet->getRowDimension('E' . +$i)->setRowHeight(60);
}
$loop = 1;
foreach ($products as $product) {
$drawing = new Drawing();
$drawing->setName('image');
$drawing->setDescription('image');
$drawing->setPath(public_path($product->image));
$drawing->setHeight(70);
$drawing->setOffsetX(5);
$drawing->setOffsetY(5);
$drawing->setCoordinates('E' . $loop);
$drawing->setWorksheet($event->sheet->getDelegate());
$loop++;
}
},
];
}
/**
* #var product $product
*/
public function map($product): array
{
return [
$product->id,
$product->category_id,
$product->category_name,
$product->name,
$product->image,
$product->created_at,
$product->updated_at,
];
}

Maatwebsite/Laravel-Excel View format

I am loading Laravel view and exporting as Excel using Maatwebsite/Laravel-Excel but my data showing as text but i need to make it as decimal, number. how can i do this. I have already read the documentation but there i cant find solution.
$fileName = 'Receipt Register : From '.date('d-m-Y', strtotime($date_from)).' To '.date('d-m-Y', strtotime($date_to)).($itemDetails ? ' For Item '.$itemDetails->item_code : "");
Excel::create($fileName, function( $excel) use($date_from, $date_to, $request) {
$excel->sheet('Receipt-Register', function($sheet) use($date_from, $date_to, $request) {
$itemDetails = [];
$itemFilterData = [];
$result = Ledger::where('receive_quantity', '!=', NULL)
->where('receive_quantity', ">", 0)
->orderBy('date', 'ASC')
->orderBy('mrn_number',"ASC")
->whereNotNull('mrn_number')
->whereNotNull('mrn_id')
->orderBy('id', "ASC")
->with('department', 'item', 'itemGroup', 'mrn')
->has('mrn', ">", 0);
if($request->date_from) {
$date_from = date('Y-m-d', strtotime($request->date_from));
$result = $result->whereDate('date', '>=', $date_from);
}
if($request->date_to) {
$date_to = date('Y-m-d', strtotime($request->date_to));
$result = $result->whereDate('date', '<=', $date_to);
}
if($request->item_id){
$result = $result->where('item_id', '=', $request->item_id);
$itemDetails = Item::find($request->item_id);
}
$results = $result->get();
$sheet->loadView('export_view',[
'results' => $results,
'date_from' => $date_from,
'date_to' => $date_to,
'itemFilterData' => $itemFilterData
]);
});
})->download('xlsx');

Strict Standards: Static function DAO::makeItem() should not be abstract in

I have this code, in file that have the name dao.abstract.class.php, but I am getting this error when I surf the site, and admin panel. Strict Standards: Static function DAO::makeItem() should not be abstract in dao.abstract.class.php on line 15
<?php
abstract class DAO
{
protected $m_sql;
protected $m_sqlId = -1;
protected $m_orderBy;
protected $m_orderByField;
protected $m_orderByType;
**abstract public function selectFromId($iditem);
abstract public function delete($iditem);
abstract public function save($object);
abstract static function makeItem($resultRow);
abstract protected function createSql();**
protected function __construct($sql, $sortField, $sortType)
{
$this->m_sql = $sql;
$this->m_orderBy = array($sortField => $sortType);
$this->m_orderByField = $sortField;
$this->m_orderByType = $sortType;
}
public function setOrderBy($order_by, $field, $type)
{
$this->m_orderBy = $order_by;
$this->m_orderByField = $field;
$this->m_orderByType = $type;
}
public function getOrderBy()
{
return $this->m_orderBy;
}
public function getOrderByField()
{
return $this->m_orderByField;
}
public function getOrderByType()
{
return $this->m_orderByType;
}
protected function executeQuery($objectArray = true, $renew = false)
{
if ($result = mysql_query($this->m_sql->getCommand($this->m_sqlId)))
{
if($objectArray == true)
{
$item = array();
while($row = mysql_fetch_assoc($result))
$item[] = $this->makeComplexItem($row);
}
elseif($row = mysql_fetch_assoc($result))
$item = $this->makeComplexItem($row);
else
$item = null;
}
else
Die(mysql_error().'<br/>'.$this->m_sql->getCommand());
mysql_free_result($result);
if($renew == true)
$this->m_sqlId = -1;
return $item;
}
protected function executeOneFieldQuery($array = true)
{
if ($result = mysql_query($this->m_sql->getCommand()))
{
if($array == true)
{
$item = array();
while($row = mysql_fetch_row($result))
$item[] = $row[0];
}
elseif($row = mysql_fetch_row($result))
$item = $row[0];
else
$item = null;
mysql_free_result($result);
return $item;
}
else
Die(mysql_error());
}
protected function executeSave($itemId)
{
if($itemId == -1)
$this->m_sql->setExecMode(Clarity::EXEC_INSERT);
else
$this->m_sql->setExecMode(Clarity::EXEC_UPDATE);
if ($itemId == -1 AND mysql_query($this->m_sql->getCommand()))
return mysql_insert_id();
elseif($itemId > 0 AND mysql_query($this->m_sql->getCommand()))
return $itemId;
else
Die(mysql_error().'<br/>'.$this->m_sql->getCommand());
}
protected function executeDelete()
{
$this->m_sql->setExecMode(Clarity::EXEC_DELETE);
if(mysql_query($this->m_sql->getCommand()))
return mysql_affected_rows();
else
die(mysql_error());
}
}
?>
You can move this declaration to an interface.
Like this:
interface myInterface
{
static function makeItem($resultRow);
}
abstract class DAO implements myInterface
{
[...]
}

How to stay sane with ExpressionEngines ambiguous channel field IDs?

When writing queries or running through result sets, I'm constantly having to refer to fields as "field_id_X". I want to believe there is a saner way to go about this than defining a CONST for every field_id/name pair.
define(NAME_FIELD ,'field_id_3');
define(HEIGHT_FIELD, 'field_id_4');
foreach( $result as $row ){
$name = $row[NAME_FIELD]; // :(
}
Get an Array for field id's and names...
function getFieldReferences() {
$sql = "SELECT field_id, field_name
FROM exp_channel_fields
WHERE site_id = ".$this->EE->config->item('site_id');
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$result = $result->result_array();
$finalResult = array();
foreach ($result as $row)
$finalResult[$row["field_id"]] = $row["field_name"];
return $finalResult;
} else {
return false;
}
}
Example conversion of a specific entry details $entry_id...
$sql = "SELECT exp_channel_data.*, exp_channel_titles.*, exp_channels.channel_name
FROM exp_channel_data, exp_channel_titles, exp_channels
WHERE exp_channel_data.entry_id = $entry_id
AND exp_cart_products.entry_id = $entry_id
AND exp_channel_titles.entry_id = $entry_id
LIMIT = 1";
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$result = $result->result_array();
$result = $result[0];
//### Get Field Titles ###
$fieldReferences = getFieldReferences();
//### Replace Field ID reference with name ###
foreach ($result as $key => $value) {
if (substr($key,0,9) == "field_id_") {
$result[$fieldReferences[substr($key,9)]] = $value;
unset($result[$key]);
}
if (substr($key,0,9) == "field_ft_")
unset($result[$key]);
}//### End of foreach ###
}
Convert Member fields to names based on specified member $id...
$sql = "SELECT m_field_id, m_field_name
FROM exp_member_fields";
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$memberFields = $result->result_array();
$sql = "SELECT exp_member_data.*, exp_members.email
FROM exp_member_data, exp_members
WHERE exp_member_data.member_id = $id
AND exp_members.member_id = $id
LIMIT 1";
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$result = $result->result_array();
$rawMemberDetails = $result[0];
//### Loop through each Member field assigning it the correct name ###
foreach($memberFields as $row)
$memberDetails[ $row['m_field_name'] ] = $rawMemberDetails['m_field_id_'.$row['m_field_id']];
}
You could look up exp_channel_fields.field_name (or field_label) by the field_id you have from exp_channel_data.

Kohana 3.2, displaying errors in the form

I'd like to display errors on my form, highlighting the fields which have errors, and displaying the error text next to the field. If there's no elegant way to display next to each field, above would be fine.
I've found examples from earlier versions, but the API has seemed to change and they do not work for 3.2.
It's just a project I'm learning Kohana with, so it's not critical. I just want to know the "kohana" way of handling this problem.
In my controller, I have this:
if (isset($_POST) && Valid::not_empty($_POST))
{
$post = Validation::factory($_POST)
->rule('zipcode', 'not_empty'));
if ($post->check()) {
$errors = $post->errors('zipcode');
}
}
$this->template->content = View::factory('myview', $data)
->bind('errors', $errors);
And here is my form in 'myview.php':
<?php echo Form::open(); ?>
<dl>
<dt><?php echo Form::label('zipcode', 'Zip Code') ?></dt>
<dd><?php echo Form::input('zipcode') ?></dd>
</dl>
<p><?php echo Form::submit(NULL, 'Get Records'); ?></p>
<?php echo Form::close(); ?>
I've taken the approach of extending the Form helper class to add an 'error' class name on the form fields, as well as showing the error message in the field label.
<?php defined('SYSPATH') or die('No direct script access.');
class Form extends Kohana_Form {
private static function attributes($name, & $attributes = NULL, $errors = NULL)
{
// Set the id attribute
if (!isset($attributes['id']))
{
$attributes['id'] = $name;
}
if ($errors !== NULL)
{
// Merge in external validation errors.
$errors = array_merge($errors, (isset($errors['_external']) ? $errors['_external'] : array()));
// Set the error classname
if (isset($errors[$name]))
{
$attributes['class'] = trim( (string) #$attributes['class'].' error-field');
}
}
}
public static function input($name, $value = NULL, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::input($name, $value, $attributes);
}
public static function select($name, array $options = NULL, $selected = NULL, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::select($name, $options, $selected, $attributes);
}
public static function password($name, $value = NULL, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::password($name, $value, $attributes);
}
public static function textarea($name, $body = '', array $attributes = NULL, $double_encode = TRUE, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::textarea($name, $body, $attributes, $double_encode);
}
public static function file($name, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::file($name, $attributes);
}
public static function label($input, $text = NULL, array $attributes = NULL, array $errors = NULL, $view = 'messages/label_error')
{
if ($errors !== NULL)
{
// Merge in external validation errors.
$errors = array_merge($errors, (isset($errors['_external']) ? $errors['_external'] : array()));
// Use the label_error view to append an error message to the label
if (isset($errors[$input]))
{
$text .= View::factory($view)->bind('error', $errors[$input]);
}
}
return parent::label($input, $text, $attributes);
}
}
You then pass in the $errors array into the label and field helper methods:
<?php echo
Form::label('username', 'Username', NULL, $errors),
Form::input('username', $user->username, NULL, $errors);
?>
This idea was suggested on the Kohana forums but I've struggled to find the original thread. Anyway, I've found this approach works best for me.
[edit] View an example of this approach in action here: http://kohana3.badsyntax.co/contact (submit the form)
This is some sample code I have used for a personal experiment with Kohana forms. It is part of a contact form. This should work for you.
The code below shows a contact form. After a user submits the form, it gives feedback (failed + errors / succeed).
if (isset($errors) && count($errors) > 0)
{
echo '<ul>';
foreach ($errors as $error)
{
echo '<li>' . $error . '</li>';
}
echo '</ul>';
}
// form
echo Form::open(null);
// fields
echo Form::label('firstname') . Form::input('firstname', null, array('id' => 'firstname')) . '<br />';
echo Form::label('email') . Form::input('email', null, array('id' => 'email')) . '<br />';
echo Form::label('message') . Form::textarea('message', '', array('id' => 'message')) . '<br />';
// submit
echo Form::submit('submit', 'Send message');
echo Form::close();
In the controller, I validate the form and assign the error- and success messages to the view.
public function action_index()
{
// make view
$view = View::factory('pages/contact')
->bind('post', $post)
->bind('errors', $errors)
->bind('success', $success);
// check if form is submitted
if ($_POST)
{
// trim fields
$post = array_map('trim', $_POST);
$post = Validation::factory($_POST)
->rules('firstname', array(
array('not_empty'),
array('min_length', array(':value', '2'))
))
->rules('email', array(
array('not_empty'),
array('email')
))
->rule('message', 'not_empty');
if ($post->check())
{
$success[] = 'Thank you for your message!';
}
else
{
$errors = $post->errors('contact');
}
}
// view
$this->response->body($view);
}
I hope this helps!

Resources