Maatwebsite excel Serialization of 'PDO' is not allowed - excel

Im tring to export large data in queue on s3 and getting Serialization of 'PDO' is not allowed exception/ Here is my code:
Controller
$transactions = Transaction::query()
->with([
'user',
'user.profile',
'senderUser',
'receiverUser',
'senderUser.roles',
'receiverUser.roles'
])->filterByUser()
->filter($filters)
->orderByDesc('created_at');
if (request()->export_transactions){
(new TransactionsExport(auth('sanctum')->user(),$transactions))->store('transactions-exports/' . now()->format('d:m:Y') . '.csv', 's3', \Maatwebsite\Excel\Excel::CSV);
return response()->json('Export started');
}
Export file
class TransactionsExport implements FromQuery, WithMapping, WithHeadings, WithCustomQuerySize, ShouldQueue
{
use Exportable;
private $user;
private $transactions;
public function __construct(User $user, $transactions)
{
$this->user = $user;
$this->transactions = $transactions;
}
/**
* #return Builder
*/
public function query()
{
return $this->transactions;
}
public function querySize(): int
{
return $this->transactions->count();
}
public function headings(): array
{
return [
//headings
];
}
public function prepareRows($transactions): array
{
//code here
}
public function map($transaction): array
{
//code here
}
}
I also tried to trigger it like this (with additional paramethers and without and with different allowed methods (store, download etc.))
(new TransactionsExport(auth('sanctum')->user(),$transactions))->queue('transactions-exports/' . now()->format('d:m:Y') . '.csv', 's3', \Maatwebsite\Excel\Excel::CSV);
Also, I tried move Transaction::query() direct to query method in export file.
Also didnt help toSql() method (Call to a member function count() on string exception appears)
Don't know what I'm doing wrong. Thanks for help.

I have solved the problem by deleting the injection of classes in the constructor, it's not allowed in jobs (queues/ if you need an object of a class, better to call it like new Class()), and now all is working fine.

Related

Read specific sheet by name on import excel laravel

I have an excel with multiple sheets but i only want read one sheet:
My problem is that i have multiple sheets, and they do not have the same order or the same number of pages. Then, i must identify the sheet by name on my import class (laravel import).
Here is my import class:
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithEvents;
class ExecutedUPS implements WithMultipleSheets, WithEvents
{
private $nameSheetUPS = "LMS - F";
public function sheets(): array
{
$sheets = [];
//doesn't work for me
if($event->getSheet()->getTitle() === $this->nameSheetUPS){
$sheets[] = new SheetUPS();
}
return $sheets;
}
}
And here is my class "SheetUPS":
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class SheetUPS implements ToCollection
{
/**
* #param Collection $collection
*/
public function collection(Collection $collection)
{
//this i know do
}
}
Have you tried selecting the sheet by name as the documentation does?
//class ExecutedUPS
public function sheets(): array
{
return [
'LMS - F' => new SheetUPS(),
];
}

How can I pass parameter in the laravel excel?

I get tutorial from here : https://laravel-excel.maatwebsite.nl/docs/3.0/export/basics
<?php
...
use App\Exports\ItemsDetailsExport;
class ItemController extends Controller
{
...
public function exportToExcel(ItemsDetailsExport $exporter, $id)
{
//dd($id); I get the result
return $exporter->download('Summary Detail.xlsx');
}
}
My export like this :
<?php
namespace App\Exports;
use App\Repositories\Backend\ItemDetailRepository;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Illuminate\Support\Facades\Input;
class ItemsDetailsExport implements FromCollection
{
use Exportable;
protected $itemDetailRepository;
public function __construct(ItemDetailRepository $itemDetailRepository)
{
$this->itemDetailRepository = $itemDetailRepository;
}
public function collection()
{
$test = Input::get('id');
dd('yeah', $test);
}
}
I want to pass id parameter to export file. I try like that, but I don't get the id. The id is null
How can I solve this problem?
For passing data from controller to laravel excel function we can pass and use data like below
For example, we have to pass data year like 2019 we will pass like below
in controller
Excel::download(new UsersExport(2019), 'users.xlsx');
In laravel import file
class UsersExport implements FromCollection {
private $year;
public function __construct(int $year)
{
$this->year = $year;
}
public function collection()
{
return Users::whereYear('created_at', $this->year)->get();
}
}
you can refer all following official documentation link
https://docs.laravel-excel.com/3.1/architecture/objects.html#plain-old-php-object
Unfortunately you can't use normal dependency injection when you have a specific parameter. This is what you can do though:
class ItemsDetailsExport implements FromCollection
{
use Exportable;
protected $itemDetailRepository;
protected $id;
public function __construct(ItemDetailRepository $itemDetailRepository, $id)
{
$this->itemDetailRepository = $itemDetailRepository;
$this->id = $id;
}
public function collection()
{
$test = $this->id;
dd('yeah', $test);
}
}
Now the problem is that the container doesn't know how to resolve $id however there are two ways around this.
Manual passing of $id:
public function exportToExcel($id)
{
$exporter = app()->makeWith(ItemsDetailsExport::class, compact('id'));
return $exporter->download('Summary Detail.xlsx');
}
Route injection:
Define your route as:
Route::get('/path/to/export/{itemExport}', 'ItemController#exportToExcel');
In your RouteServiceProvider.php:
public function boot() {
parent::boot();
//Bindings
Route::bind('itemExport', function ($id) { //itemExport must match the {itemExport} name in the route definition
return app()->makeWith(ItemsDetailsExport::class, compact('id'));
});
}
Then your route method is simplified as:
public function exportToExcel(ItemsDetailsExport $itemExport)
{
//It will be injected based on the parameter you pass to the route
return $itemExport->download('Summary Detail.xlsx');
}

Undefined variable error in ExpressionEngine plugin

I'm working on a plugin that does device detection based on an external library.
This is what I have so far:
class Deetector {
// public $return_data;
/**
* Constructor
*/
public function __construct()
{
$this->EE =& get_instance();
$this->EE->load->add_package_path(PATH_THIRD.'/deetector');
$this->EE->load->library('detector');
$this->return_data = "";
}
public function deetector()
{
return $ua->ua;
}
public function user_agent()
{
return $ua->ua;
}
// ----------------------------------------------------------------
/**
* Plugin Usage
*/
public static function usage()
{
ob_start();
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
}
If I call {exp:deetector} I get no output in the template. If I call {exp:deetector:user_agent} I get Undefined variable: ua.
Ultimately I don't plan on setting up different functions for each of the variables that the Detector library returns but am just trying to get it to output something at the moment.
I had originally started doing this as an extension which added the Detector library's variables to the global variables array and that was working fine; it's only since trying to do it as a plugin that I've run into problems.
You haven't set $this->ua to anything. I assume it's a variable of the detector library you loaded, so you probably want to do something like this:
class Deetector {
public function __construct()
{
$this->EE =& get_instance();
// remove this line, it's probably not doing anything
// $this->EE->load->add_package_path(PATH_THIRD.'/deetector');
$this->EE->load->library('detector');
// note you use $this->return_data instead of "return blah" in the constructor
$this->return_data = $this->EE->detector->ua;
}
// remove this, you can't have both __construct() and deetector(), they mean the same thing
// public function deetector()
// {
// return $ua->ua;
// }
public function user_agent()
{
return $this->EE->detector->ua;
}
}
UPDATE:
I took a look at the Detector docs, and it doesn't follow normal library conventions (it defines the $ua variable when you include the file). For that reason you should ignore the standard EE load functions, and include the file directly:
class Deetector {
public function __construct()
{
$this->EE =& get_instance();
// manually include the detector library
include(PATH_THIRD.'/deetector/libraries/detector.php');
// save the local $ua variable so we can use it in other functions further down
$this->ua = $ua;
// output the user agent in our template
$this->return_data = $this->ua->ua;
}
}

Form: Avoid setting null to non submitted field

I've got a simple model (simplified of source):
class Collection
{
public $page;
public $limit;
}
And a form type:
class CollectionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('page', 'integer');
$builder->add('limit', 'integer');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'FSC\Common\Rest\Form\Model\Collection',
));
}
}
My controller:
public function getUsersAction(Request $request)
{
$collection = new Collection();
$collection->page = 1;
$collection->limit = 10;
$form = $this->createForm(new CollectionType(), $collection)
$form->bind($request);
print_r($collection);exit;
}
When i POST /users/?form[page]=2&form[limit]=20, the response is what i expect:
Collection Object
(
[page:public] => 2
[limit:public] => 20
)
Now, when i POST /users/?form[page]=3, the response is:
Collection Object
(
[page:public] => 3
[limit:public] =>
)
limit becomes null, because it was not submitted.
I wanted to get
Collection Object
(
[page:public] => 3
[limit:public] => 10 // The default value, set before the bind
)
Question: How can i change the form behaviour, so that it ignores non submitted values ?
If is only a problem of parameters (GET parameters) you can define the default value into routing file
route_name:
pattern: /users/?form[page]={page}&form[limit]={limit}
defaults: { _controller: CompanyNameBundleName:ControllerName:ActionName,
limit:10 }
An alternative way could be to use a hook (i.e. PRE_BIND) and update manually that value into this event. In that way you haven't the "logic" spreaded into multi pieces of code.
Final code - suggested by Adrien - will be
<?php
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
class IgnoreNonSubmittedFieldSubscriber implements EventSubscriberInterface
{
private $factory;
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
public static function getSubscribedEvents()
{
return array(FormEvents::PRE_BIND => 'preBind');
}
public function preBind(FormEvent $event)
{
$submittedData = $event->getData();
$form = $event->getForm();
// We remove every child that has no data to bind, to avoid "overriding" the form default data
foreach ($form->all() as $name => $child) {
if (!isset($submittedData[$name])) {
$form->remove($name);
}
}
}
}
Here's a modification of the original answer. The most important benefit of this solution is that validators can now behave as if the form post would always be complete, which means there's no problems with error bubbling and such.
Note that object field names must be identical to form field names for this code to work.
<?php
namespace Acme\DemoBundle\Form;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
class FillNonSubmittedFieldsWithDefaultsSubscriber implements EventSubscriberInterface
{
private $factory;
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
public static function getSubscribedEvents()
{
return array(FormEvents::PRE_BIND => 'preBind');
}
public function preBind(FormEvent $event)
{
$submittedData = $event->getData();
$form = $event->getForm();
// We complete partial submitted data by inserting default values from object
foreach ($form->all() as $name => $child) {
if (!isset($submittedData[$name])) {
$obj = $form->getData();
$getter = "get".ucfirst($name);
$submittedData[$name] = $obj->$getter();
}
}
$event->setData($submittedData);
}
}

ViewHelper newable/injectable dilemma

I'm trying to design an application following Misko Heverys insights. It's an interesting experiment and a challenge. Currently I'm struggling with my ViewHelper implementation.
The ViewHelper decouples the model from the view. In my implementation it wraps the model and provides the API for the view to use. I'm using PHP, but I hope the implementation is readable for everyone:
class PostViewHelper {
private $postModel;
public function __construct(PostModel $postModel) {
$this->postModel = $postModel;
}
public function title() {
return $this->postModel->getTitle();
}
}
In my template (view) file this could be called like this:
<h1><?php echo $this->post->title(); ?></h1>
So far so good. The problem I have is when I want to attach a filter to the ViewHelpers. I want to have plugins that filter the output of the title() call. The method would become like this:
public function title() {
return $this->filter($this->postModel->getTitle());
}
I need to get observers in there, or an EventHandler, or whatever service (in what I see as a newable, so it needs to be passed in through the stack). How can I do this following the principles of Misko Hevery? I know how I can do this without it. I'm interested in how for I can take it and currently I don't see a solution. ViewHelper could be an injectable too, but then getting the model in there is the problem.
I didn't find the blog post you referenced very interesting or insightful.
What you are describing seems more like a Decorator than anything to do with dependency injection. Dependency injection is how you construct your object graphs, not their state once constructed.
That said, I'd suggest taking your Decorator pattern and running with it.
interface PostInterface
{
public function title();
}
class PostModel implements PostInterface
{
public function title()
{
return $this->title;
}
}
class PostViewHelper implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->post->title();
}
}
class PostFilter implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->filter($this->post->title());
}
protected function filter($str)
{
return "FILTERED:$str";
}
}
You'd simply use whatever DI framework you have to build this object graph like so:
$post = new PostFilter(new PostViewHelper($model)));
I often use this approach when building complex nested objects.
One problem you might run into is defining "too many" functions in your PostInterface. It can be a pain to have to implement these in every decorator class. I take advantage of the PHP magic functions to get around this.
interface PostInterface
{
/**
* Minimal interface. This is the accessor
* for the unique ID of this Post.
*/
public function getId();
}
class SomeDecoratedPost implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->_post = $post;
}
public function getId()
{
return $this->_post->getId();
}
/**
* The following magic functions proxy all
* calls back to the decorated Post
*/
public function __call($name, $arguments)
{
return call_user_func_array(array($this->_post, $name), $arguments);
}
public function __get($name)
{
return $this->_post->get($name);
}
public function __set($name, $value)
{
$this->_post->__set($name, $value);
}
public function __isset($name)
{
return $this->_post->__isset($name);
}
public function __unset($name)
{
$this->_post->__unset($name);
}
}
With this type of decorator in use, I can selectively override whatever method I need to provide the decorated functionality. Anything I don't override is passed back to the underlying object. Multiple decorations can occur all while maintaining the interface of the underlying object.

Resources