Not saving data to the excel using maatweb using laravel - php

This is my first time using Maatweb/Excel in Laravel 7
The excel file is downloaded but it is empty.
I dont know what is wrong with this. Maybe some one can help me.
Here is my code AdsExport.php:
<?php
declare(strict_types=1);
namespace App\Exports;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
class AdsExport implements WithHeadings
{
/**
* #return \Illuminate\Support\Collection
*/
use Exportable;
private $dateFrom;
private $dateTo;
public function __construct(string $dateFrom, string $dateTo)
{
$this->dateFrom = $dateFrom;
$this->dateTo = $dateTo;
}
public function headings(): array
{
return ['View', 'Clicks', 'URL', 'Company Name', 'Ad Title'];
}
public function query()
{
return DB::table('ads_management')
->select(DB::raw('select COUNT(ad_views.id) as count_views from ad_views left join
ads_management on ads_management.id = view_ads.ads_id where ad_views.created_by between ? and ?'),
DB::raw('select COUNT(ad_clicks.id) as count_clicks from ad_clicks left join
ads_management on ads_management.id = view_clicks.ads_id where ad_clicks.created_by between ? and ?'), 'ad_link', 'company_name', 'title')
->setBindings([$this->dateFrom, $this->dateTo, $this->dateFrom, $this->dateTo])
->get();
}
}
Thanks in advance

Related

Addition of an ordinal number in the Laravel Model

I am beginner webdeveloper,
I use in my project Laravel 7 and maatwebsite/excel
I have this code:
namespace App\Models;
use App\Models\Reservation;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\Exportable;
class ReservationExport implements FromCollection, WithHeadings
{
use Exportable;
protected $date;
public function __construct(string $date)
{
$this->date = $date;
}
public function headings(): array
{
return [
'LP',
'ID Rezerwacji',
'Adres email',
'Token',
'Data',
'Godzina',
'Tor',
'Płeć',
];
}
public function collection()
{
$res = Reservation::select('id', 'id', 'email', 'token', 'date', 'hour', 'track', 'sex')->where('date', $this->date)->orderBy('time', 'ASC')->orderBy('track', 'ASC')->get();
foreach ($res as $val) {
$val->sex = ($val->sex == 1) ? 'kobieta' : 'mężczyzna';
}
return $res;
}
}
public function export(Request $request)
{
return Excel::download(new ReservationExport($request->input('query')), 'reservation-'.$request->input('query').'.xlsx');
}
This code generates an Excel document. It works fine. I would like to add a sequence number in 1 column (1,2,3 etc).
How can I do this?
My model:
class Reservation extends Model
{
protected $quarded = ['id'];
protected $fillable = ['email', 'token', 'date', 'hour', 'track', 'sex', 'time', 'people'];
public $timestamps = true;
protected $table = 'reservations';
}
Please help
try this
basically u need to add sn to heading then in your collection u need to a new key sn with calculated sequence number
hope it will work if not please tell me what error u r getting
<?php
use App\Models\Reservation;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\Exportable;
class ReservationExport implements FromCollection, WithHeadings
{
use Exportable;
protected $date;
public function __construct(string $date)
{
$this->date = $date;
}
public function headings(): array
{
return [
'SN', // sn new key adding
'LP',
'ID Rezerwacji',
'Adres email',
'Token',
'Data',
'Godzina',
'Tor',
'Płeć',
];
}
public function collection()
{
$res = Reservation::select('id', 'id', 'email', 'token', 'date', 'hour', 'track', 'sex')->where('date', $this->date)->orderBy('time', 'ASC')->orderBy('track', 'ASC')->get();
foreach ($res as $val) {
$val->sex = ($val->sex == 1) ? 'kobieta' : 'mężczyzna';
}
$res->map(function ($row,$key) {
return $row['sn'] = $key; // sn key added to collection
});
return $res;
}
}

Laravel: How to change Time Stamps Format in Excel Export?

I am generating a Excel Export, I want to change the timestamps format in excel file from 2020-07-29 13:56:09 to just DD:MM:YYYY.
How can I change my Export Class to Format the timestamp Column in my Excel File, BTW Date is in 'E' column in Excel file.
My Export Class:
use App\outbound_detail;
use App\outbound_temp;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Events\AfterSheet;
class ReleaseExportView implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
{
protected $reference;
function __construct($reference)
{
$this->reference = $reference;
}
public function collection()
{
return outbound_detail::where('reference', $this->reference)->get([
'reference', 'sku_parent', 'sku_child', 'cases', 'updated_at'
]);
}
public function headings(): array
{
return [
'Reference',
'SKU Parent',
'SKU Child',
'Cases Released',
'Date Created'
];
}
// ...
/**
* #return array
*/
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
$cellRange = 'A1:W1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
},
];
}
}
On your Reference Model, add this :
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d:m:Y');
}
You can use it's column formatting.
Try this:
// ...
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
class ReleaseExportView implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents, WithColumnFormatting
{
// ...
public function map($reference): array
{
return [
$reference->reference,
$reference->sku_parent,
$reference->sku_child,
$reference->cases,
Date::dateTimeToExcel($reference->updated_at)
];
}
public function columnFormats(): array
{
return [
'E' => NumberFormat::FORMAT_DATE_DDMMYYYY
];
}
}

Laravel: How change PDF styling in maatwebsite DOMPDF export?

I am exporting PDF files with every entry.
But they are too simple, i.e: no styling.
Here is a screenshot:
But as you can see, there is no styling other then the styling is used for my Excel export. I want to add a logo image on top. Remove the extra columns and add some header text like Company name, address etc....
Here is my Controller:
public function export_release(Request $request)
{
Excel::store(new \App\Exports\ReleaseExportView($request->reference),'uploads/release/'.$request->reference.'/'.'release_'.$request->reference.'.pdf','real_public', \Maatwebsite\Excel\Excel::DOMPDF);
return redirect()->route('release_inventory')->with('success','Outbound has been Created.');
}
Here is my Export class:
use App\outbound_detail;
use App\outbound_temp;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
class ReleaseExportView implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
{
protected $reference;
function __construct($reference) {
$this->reference = $reference;
}
public function collection()
{
//link for StackOverFlow
//https://stackoverflow.com/questions/57153985/how-to-pass-parameter-to-export-file-of-laravel-excel-for-db-query
return outbound_detail::where('reference',$this->reference)->get([
'reference', 'sku_parent', 'sku_child', 'cases'
]);
}
public function headings(): array
{
return [
'Reference',
'SKU Parent',
'SKU Child',
'Cases Released'
];
}
// ...
/**
* #return array
*/
public function registerEvents(): array
{
return [
AfterSheet::class => function(AfterSheet $event) {
$cellRange = 'A1:W1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
},
];
}
}
First of all Remove ShouldAutoSize, to fit the data in your file.
Then edit A1:W1 in AfterSheet. I'm still researching on adding company info also
you can return Blade view instead of array and customize the layout there
public function view(): View
{
$data = [];
return view('yourBladeView', [
'details' => $data
]);
}

How can you include column headers when exporting Eloquent to Excel in Laravel?

I am trying to allow users to download Excel, using Laravel Excel files with product information. My current web route looks like this:
Route::get('/excel/release', 'ExcelController#create')->name('Create Excel');
My current Export looks like this:
class ProductExport implements FromQuery
{
use Exportable;
public function __construct(int $id)
{
$this->id = $id;
}
public function query()
{
return ProductList::query()->where('id', $this->id);
}
}
My current controller looks like this:
public function create(Request $request) {
# Only alowed tables
$alias = [
'product_list' => ProductExport::class
];
# Ensure request has properties
if(!$request->has('alias') || !$request->has('id'))
return Redirect::back()->withErrors(['Please fill in the required fields.'])->withInput();
# Ensure they can use this
if(!in_array($request->alias, array_keys($alias)))
return Redirect::back()->withErrors(['Alias ' . $request->alias . ' is not supported'])->withInput();
# Download
return (new ProductExport((int) $request->id))->download('iezon_solutions_' . $request->alias . '_' . $request->id . '.xlsx');
}
When I head over to https://example.com/excel/release?alias=product_list&id=1 this executes correctly and returns an excel file. However, there is no column headers for the rows. The data comes out like so:
1 150 1 3 2019-01-16 16:37:25 2019-01-16 16:37:25 10
However, this should contain column headers like ID, cost etc... How can I include the column headers in this output?
According to documentation you can change your class to use the WithHeadings interface, and then define the headings function to return an array of column headers:
<?php
namespace App;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ProductExport implements FromQuery, WithHeadings
{
use Exportable;
public function __construct(int $id)
{
$this->id = $id;
}
public function query()
{
return ProductList::query()->where('id', $this->id);
}
public function headings(): array
{
return ["your", "headings", "here"];
}
}
This works with all export types (FromQuery, FromCollection, etc.)
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use DB;
class LocationTypeExport implements FromCollection,WithHeadings
{
public function collection()
{
$type = DB::table('location_type')->select('id','name')->get();
return $type ;
}
public function headings(): array
{
return [
'id',
'name',
];
}
}
You can combine this with array_keys to dynamically get your column headers:
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ProductExport implements FromQuery, WithHeadings
{
use Exportable;
public function __construct(int $id)
{
$this->id = $id;
}
public function query()
{
return ProductList::query()->where('id', $this->id);
}
public function headings(): array
{
return array_keys($this->query()->first()->toArray());
}
}
If you're using it with a collection, you can do so like the following:
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ProductExport implements FromCollection, WithHeadings
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
// for selecting specific fields
//return ProductList::select('id', 'product_name', 'product_price')->get();
// for selecting all fields
return ProductList::all();
}
public function headings(): array
{
return $this->collection()->first()->keys()->toArray();
}
}
<?php
namespace App\Exports;
use App\Models\UserDetails;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
class CustomerExport implements FromCollection, WithHeadings
{
public function collection()
{
return UserDetails::whereNull('business_name')
->select('first_name','last_name','mobile_number','dob','gender')
->get();
}
public function headings() :array
{
return ["First Name", "Last Name", "Mobile","DOB", "Gender"];
}
}
<?php
namespace App\Exports;
use App\Models\StudentRegister;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class StudentExport implements FromCollection, WithHeadings
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return StudentRegister::select('name','fname','mname','gender','language','address')->get();
}
public function headings(): array
{
//Put Here Header Name That you want in your excel sheet
return [
'Name',
'Father Name',
'Mother Name',
'Gender',
'Opted Language',
'Corresponding Address'
];
}
}
I am exporting from Collections and I wanted to generate headings automatically from the column names. The following code worked for me!
public function headings(): array
{
return array_keys($this->collection()->first()->toArray());
}
If you want to manually write the column names return an array with the column names.
And don't forget to impliment WithHeadings Interface
Thanks #Ric's comment.
This code works for me
use App\Newsletter;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class NewsletterExport implements FromCollection, WithHeadings
{
public function headings(): array
{
return [
'Subscriber Id',
'Name',
'Email',
'Created_at',
];
}
public function collection()
{
return Newsletter::where('isSubscribed', true)->get(['id','name','email','created_at']);
}
}

Using Notification is Pivotal

I am trying to use the laravel 5.3 notification system. I have a many to many relationship on a couple of models. What I need to do is loop through all of the request data and send a notification to everyone appropriate. It seems that the notification methods won't work within a foreach loop. The error is:
BadMethodCallException in Builder.php line 2448:
Call to undefined method Illuminate\Database\Query\Builder::routeNotificationFor()
The code I am trying to figure out is:
public function storeHoursused(Request $request, Lessonhours $lessonhours)
{
$this->validate($request, [
'date_time' => 'required',
'numberofhours' => 'required|numeric',
'comments' => 'required|max:700'
]);
$hoursused = new Hoursused();
$hoursused->date_time = $request['date_time'];
$hoursused->numberofhours = $request['numberofhours'];
$hoursused->comments = $request['comments'];
$lessonhours->hoursused()->save($hoursused);
foreach($lessonhours->players as $player){
$player->users;
Notification::send($player, new HoursusedPosted($player->user));
//$lessonhours->player->notify(new HoursusedPosted($lessonhours->player->users));
}
return back()->with(['success' => 'Hours Used successfully added!']);
}
Is there a way to collect related data and pass to notification methods?
UPDATE:
The Players model looks like:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Collective\Html\Eloquent\FormAccessible;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Notifiable;
use Carbon\Carbon;
class Players extends Model
{
public $table = "players";
protected $fillable = array('fname', 'lname', 'gender', 'birthdate');
public function users()
{
return $this->belongsTo('App\User', 'users_id');
}
public function lessonhours()
{
return $this->belongsToMany('App\Lessonhours', 'lessonhour_player', 'players_id', 'lessonhours_id')
->withTimestamps();
}
public function getFullName($id)
{
return ucfirst($this->fname ) . ' ' . ucfirst($this->lname);
}
protected $dates = ['birthdate'];
protected $touches = ['lessonhours'];
public function setBirthdateAttribute($value)
{
$this->attributes['birthdate'] = Carbon::createFromFormat('m/d/Y', $value);
}
}
Your $player model needs to use the Illuminate\Notifications\Notifiable trait.

Categories