how to convert an HTML table into an Excel spreadsheet - php

I use laravel-excel version 3.1 .
my code is :
class UsersExport implements FromView
{
private $users;
public function __construct()
{
$this->users = User::query()->select('name' , 'family' , 'mobile' ,'national_code' , 'email' , 'registered_from')->get();
}
public function view(): View
{
return view('test', [
'users' => $this->users
]);
}
}
In my controller I called vies function:
return (new UsersExport())->view();
here I got a view (html page) not excel spreadsheet. what should I do?

You need to add use Exportable; in your UserExport class, then call return (new UsersExport())->download('something.xls');
P. S. It is not a good idea to write query in UserExport constructor. It would be better to get them before calling it, then pass to your new UserExport()

Related

Yii2 handle beforesave event in behaviour

i try to develop application with yii2 framework,i use beforeSave event to handle createdAt and updatedAt with time() function, this method is :
public function beforeSave($insert)
{
if ($insert) {
$this->createdAt = time();
}
$this->updatedAt = time();
return parent::beforeSave($insert);
}
i just wanna move this method to behaviour and attach it to my model, i create the behaviour class and attach the behaviour to model but it does not work abd pass null to database, my behaviour class is :
namespace app\modules\imdb\behaviors;
use yii\base\Behavior;
use yii\db\ActiveRecord;
class saveTimeBehavior extends Behavior
{
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
];
}
public function beforeSave($event)
{
if ($event) {
$this->createdAt = time();
}
$this->updatedAt = time();
return parent::beforeSave($event);
}
}
and the attach code in my model is :
public function behaviors()
{
return [
saveTimeBehavior::className(),
];
}
please help me to handle this with correct way, thanks alot :)
You can do this with TimeStampBehavior. If you have declared the columns(created_at, updated_at) as int(11) for being UNIX timestamp.
use yii\behaviors\TimestampBehavior;
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
But as your attribute names are different or you want to use a different way of calculating the timestamp, you may configure the $createdAtAttribute, $updatedAtAttribute and $value properties like the following:
use yii\db\Expression;
use yii\behaviors\TimestampBehavior;
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'createdAt',
'updatedAtAttribute' => 'updatedAt',
'value' => new Expression('NOW()'),
],
];
}
Uou can do that in a simple way , by identify the type of created_at and updated_at as timestamp when you create the table, and it will be automatically filled in the database when you add new record or update existing one.
Example :
'created_at'=> $this->timestamp(),
'updated_at'=> $this->timestamp(),
Note: You can find more information about creating table using the below link : Yii2 Migration

How to use modelfactory in seeder in Laravel 5.4

I am using model factories in NewsTableSeeder, but I get this error when I entered db:seed.
I want to know why I can't use create() in my seeder.
Here is my News model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class News extends Model
{
protected $table = 'news';
protected $primaryKey = 'id';
public function home_news_lists() {
return $this->select('id', 'news_title', 'news_update')
->orderBy('news_update', 'DESC')
->limit(5)
->get();
}
public function lists() {
return News::all();
}
}
Model Factories:
$factory->define(App\Models\News::class, function (Faker\Generator $faker)
{
static $password;
$faker = $faker->create('zh_TW');
return [
'news_title' => $faker->sentence(),
'news_content' => $faker->paragraph(),
'news_author' => $faker->name(),
'news_pageviews' => $faker->numberBetween(1, 100),
'news_file' => ' ',
'news_img' => $faker->imageUrl($width, $height, 'business'),
'created_at' => $faker->dateTimeBetween('2012', 'now', 'zh_TW'),
'updated_at' => $faker->dateTimeBetween('2015', 'now', 'zh_TW')
];
});
NewsTableSeeder :
<?php
use Illuminate\Database\Seeder;
class NewsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\Models\News::class, 50)->create();
}
}
I can't tell 100% without seeing exactly the error you got, but I do believe there is no create() method on the $faker object.
I believe what you mean to do is:
$factory->define(App\Models\News::class, function (Faker\Generator $faker)
{
static $password;
$faker = \Faker\Factory::create('zh_TW'); // change to this
return [
...
];
}
I would just create a new faker generator (\Faker\Generator) that gets returned from calling \Faker\Factory::create($locale) and use that instead. Otherwise, I believe your next best option is to override wherever Laravel instantiates the \Faker\Generator $faker object that gets passed into the callback, but that may get hacky if Laravel doesn't provide a clean way to do it.
The create() method is a static call on the \Faker\Factory method. It accepts a locale as the parameter and uses en_US as the default locale.
$faker = $faker->create('zh_TW');
The error message said this code is wrong.
What is your purpose to use this code?

Fractal Transformers Optional Model Columns

I am using Fractal Transformers in Laravel 5. I have:
namespace App\Transformers;
use App\Models\Cake;
use League\Fractal\TransformerAbstract;
class CakeTransformer extends TransformerAbstract
{
protected $availableIncludes = [
'user',
'description'
];
public function transform(Cake $cake)
{
$ar = [
'name' => $cake->name,
'url_name' => $cake->url_name,
'user' => $cake->user->screenname,
'date_created' => $cake->created_at
];
return $ar;
}
public function includeUser(Cake $cake)
{
return $this->item($cake->user, new UserTransformer());
}
public function includeDescription(Cake $cake) {
return $cake->description;
}
}
The above doesn't work because includeDescription doesn't return the right kind of object, but from the above you can see what I'm trying to do.
For instance in my search I want to bring back much less data than if I were to load a whole page about the search item. E.g. for search I don't want to load the description, but for the page that contains details about the product I would want to.
How can I achieve this?

Fatal error: Call to a member function schemaCollection() on a non-object in ...vendor/cakephp/cakephp/src/ORM/Table.php on line 421

Hi everyone and happy Easter !
I have this problem in migrating a legacy application from CakePHP 2.x to CakePHP 3.x
I am trying to load all the contents of a database table in the initialize function of the model (ConfigurationsTable.php - made into a Singleton) class. I also tried the same code in the constructor but still get the same error. Also tried moving it to a separate function but still no luck.
It works fine in CakePHP 2.x but I get a fatal error in CakePHP 3.
Code is as follows
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class ConfigurationsTable extends Table
{
private $_configurations;
public static function getInstance()
{
static $instance = null;
if ($instance === null) {
$instance = new static();
}
return $instance;
}
public function is_set($key)
{
return isset($this->_configurations->{$key});
}
public function fetch($key)
{
return $this->_configurations->{$key};
}
public function initialize(array $config)
{
$this->addBehavior('Timestamp');
$this->_configurations = new \stdClass();
$configs = $this->find('all');
foreach ($configs as $c) {
if (isset($c->key) && $c->key != '') {
$this->_configurations->{$c->key} = $c->value;
}
}
}
public function validationDefault(Validator $validator)
{
$validator
->notEmpty('key')
->add('key', [
'unique' => [
'rule' => 'validateUnique',
'provider' => 'table',
'message' => __('This configuration key already exists')
]
])
->notEmpty('value')
;
return $validator;
}
The line that's causing the error is: $configs = $this->find('all');
Can anyone provide me a solution for this ?
I need it for work..
Thanks a lot in advance
You cannot blindly apply 2.x concepts and expect it to work. Before you start working with code that you don't know about, take at least a look at the API docs
http://api.cakephp.org/3.0/class-Cake.ORM.Table.html#___construct
and having a look at the source itself to understand what the code actually does would be even better.
When manually instantiating table classes, you must at least provide a connection instance. However, what you are doing there doesn't make much sense, there's not really a need for a custom static instance getter, that's what TableRegistry::get() is there for.

Extend/override Eloquent create method - Cannot make static method non static

I'm overriding the create() Eloquent method, but when I try to call it I get Cannot make static method Illuminate\\Database\\Eloquent\\Model::create() non static in class MyModel.
I call the create() method like this:
$f = new MyModel();
$f->create([
'post_type_id' => 1,
'to_user_id' => Input::get('toUser'),
'from_user_id' => 10,
'message' => Input::get('message')
]);
And in the MyModel class I have this:
public function create($data) {
if (!Namespace\Auth::isAuthed())
throw new Exception("You can not create a post as a guest.");
parent::create($data);
}
Why doesn't this work? What should I change to make it work?
As the error says: The method Illuminate\Database\Eloquent\Model::create() is static and cannot be overridden as non-static.
So implement it as
class MyModel extends Model
{
public static function create($data)
{
// ....
}
}
and call it by MyModel::create([...]);
You may also rethink if the auth-check-logic is really part of the Model or better moving it to the Controller or Routing part.
UPDATE
This approach does not work from version 5.4.* onwards, instead follow this answer.
public static function create(array $attributes = [])
{
$model = static::query()->create($attributes);
// ...
return $model;
}
Probably because you are overriding it and in the parent class it is defined as static.
Try adding the word static in your function definition:
public static function create($data)
{
if (!Namespace\Auth::isAuthed())
throw new Exception("You can not create a post as a guest.");
return parent::create($data);
}
Of course you will also need to invoke it in a static manner:
$f = MyModel::create([
'post_type_id' => 1,
'to_user_id' => Input::get('toUser'),
'from_user_id' => 10,
'message' => Input::get('message')
]);

Categories