What's wrong with my code, I tried to export my data table using framework Laravel. The file is downloaded with empty content.
StockModel.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Stock extends Model {
protected $table = 'stock_tb';
protected $primaryKey = 'id';
protected $fillable = ['stock_id', 'input_date', 'quantity'];
}
AdminController.php
use Excel;
use App\Stock;
use App\Exports\StockExport;
class adminController extends Controller {
public function __construct() { }
public function printStockReport(){
return Excel::download(new StockExport('07/01/2020'), 'ado.xlsx');
}
StockExport.php
namespace App\Exports;
use App\Stock;
use Maatwebsite\Excel\Concerns\FromQuery;
class StockExport implements FromQuery
{
protected $id;
public function __construct($date_var)
{
$this->date = $date_var;
}
public function query()
{
return Stock::query()->where('input_date', $this->date)->get();
}
}
Router
Route::get('admin/printStockReport', 'adminController#printStockReport');
Fyi: I run the SQL code on my RDBMS with criteria input date 07/01/2020. It returns 129 records.
Thank you
remove ->get() , according to laravel-excel documentation no need to that.
Related
I am currently updating a project from CakePHP 3 to CakePHP 4, and in this project I have a Trait that implements a "common" virtual property that some of the entities need.
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class NewsTable extends Table
{
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('news');
$this->setPrimaryKey('id');
// more config here...
}
}
<?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
class News extends Entity
{
use SitemapTrait;
protected $_virtual = ['sitemap']; // this is the virtual property that the trait should take care of
}
<?php
namespace App\Model\Entity;
use Cake\ORM\TableRegistry;
trait SitemapTrait
{
protected function _getSitemap()
{
$table = TableRegistry::getTableLocator()->get($this->getSource());
// more logic here...
}
}
The problem is that, on the _getSitemap() method, $this->getSource() returns a generic Cake\ORM\Table object, rather than a App\Model\Table\NewsTable object as I would expect, so everything that should happen afterward will not work.
I also wrote a simple command to check what happens when getSource() is called directly on an entity, and in this case I get the correct result, so the problem seems to be specifically related to it being called inside a Trait:
<?php
namespace App\Command;
use Cake\Command\Command;
use Cake\Console\ConsoleIo;
use Cake\Console\Arguments;
use Cake\ORM\TableRegistry;
class OrmTestCommand extends Command
{
protected $newsTable;
public function __construct()
{
$this->newsTable = TableRegistry::getTableLocator()->get('News');
}
public function execute(Arguments $args, ConsoleIo $io)
{
$news = $this->newsTable->find('all')
->first();
print_r($news->getSource());
}
}
In this case I correctly get a App\Model\Table\NewsTable object.
I don't get why this broke going from CakePHP 3.5.18 to 4.3.11. Do I need some extra config in my model? What am I doing missing or doing wrong?
I’m kind of new to Laravel and the whole API architecture, so my question may seem dumb at first.
My basic setup:
Laravel 8;
PHP 8;
routes\api.php
Route::post('/categories/',[ApiCategoriesInsertController::class, 'insertCategories'], function($insertCategoriesResults) {
return response()->json($insertCategoriesResults);
})->name('api.categories.insert');
\app\Http\Controllers\ApiCategoriesInsertController.php (created with php artisan make:controller)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
// Custom models.
use App\Models\CategoriesInsert;
class ApiCategoriesInsertController extends Controller
{
private mixed $ciAPI;
public function __construct(Request $req)
{
}
public function insertCategories(Request $req): array
{
$this->ciAPI = new CategoriesInsert(['testing'=>'debug']);
return [‘status’ => ‘OK’];
}
}
\app\Models\CategoriesInsert.php (created with php artisan make:model)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CategoriesInsert extends Model
{
use HasFactory;
public function __construct(array $objParameters)
{
}
}
When I make a post to http://localhost:8000/api/categories, Laravel logs the following error:
local.ERROR: Too few arguments to function App\Models\CategoriesInsert::__construct(), 0 passed in … Too few arguments to function App\\Models\\CategoriesInsert::__construct(), 0 passed in …
Anyone knows what’s wrong or missing in my architecture?
Thanks!
Make your model's constructor compatible with parent.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CategoriesInsert extends Model
{
use HasFactory;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
}
}
Also, notice, that when you call new CategoriesInsert(['testing'=>'debug']), you do not save the data in your database. Use:
$insert = new CategoriesInsert(['testing'=>'debug']);
$insert->save();
Or:
CategoriesInsert::create(['testing'=>'debug']);
you don't need to pass data to model
change your code to bellow code:
public function insertCategories(Request $req): array
{
CategoriesInsert::create(['testing' => 'debug']);
return [‘status’ => ‘OK’];
}
key of passed array is your filed name in database, and value stored data
also you should define fillable parameter in model
protected $fillable = [
'title',
'slug',
'priority',
];
I updated a backpack project from backpack 4.0 to 4.1 and followed the upgrade guide that is provided on the backpack site. Laravel still runs on 6.x and has not been upgraded lately.
The list and /edit update views are working as intended. Only when trying to open a show view (happens on all models), then the following error occurs:
Too few arguments to function Illuminate\Database\Eloquent\Model::created(), 0 passed in /var/www/vendor/backpack/crud/src/app/Library/CrudPanel/CrudPanel.php on line 330 and exactly 1 expected
I tried to follow the stack trace but I can't find the source that throws the error. I also tried to remove all the methods from one model and just keep construct() and setup() and even then the errors is still thrown.
Edit: The error occurs for all models, this is the code of one random model.
namespace App\Models;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Vereine extends KVUser
{
}
namespace App\Models;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class KVUser extends Model
{
use CrudTrait;
use SoftDeletes;
protected $table = 'user';
public $incrementing = true;
/*
|--------------------------------------------------------------------------
| GLOBAL VARIABLES
|--------------------------------------------------------------------------
*/
protected $guarded = [];
public function __construct(array $attributes = [])
{
$this->creating([$this, 'onCreating']);
$this->updating([$this, 'onUpdating']);
parent::__construct($attributes);
}
public static function deleting($callback)
{
parent::deleting($callback);
$callback->update(['deleted' => 1]);
}
public function onCreating(\App\Models\KVUser $row)
{
// Placeholder for catching any exceptions
if (!\Auth::user()->id) {
return false;
}
$row->setAttribute('created_id', \Auth::user()->id);
}
public function onUpdating(\App\Models\KVUser $row)
{
// Placeholder for catching any exceptions
if (!\Auth::user()->id) {
return false;
}
$row->setAttribute('updated_id', \Auth::user()->id);
}
}
namespace App\Http\Controllers\Admin;
use App\Http\Requests\VereineRequest;
use App\Models\Vereine;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class VereineCrudController extends CrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
public function __construct()
{
parent::__construct();
}
public function setup()
{
$this->crud->setModel('App\Models\Vereine');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/vereine');
$this->crud->setEntityNameStrings('Verein', 'Vereine');
$this->crud->setListView('vendor/backpack/crud/vereine/vereine_list');
$this->crud->setShowView('vendor/backpack/crud/vereine/vereine_show');
}
}
Screenshot Error Message
I would really appreciate some help - thank you!
For clearly to identify error you should attached image. Thanks
I just upgraded Laravel 5.4 to 5.5 and now I have to change all the coding that used the old Laravel-Excel.
I'm using php 7.2.25, Windows/Wamp.
I am trying to upload an excel file, get it's data, do lots of check and calculations on it (Not in the code yet) and then create a new excel file and give the user the Windows 'Save File' option.
Not sure how to get the Windows save file window, don't see any explanation on the documentation.
If I can't get the Windows save file window, I'm not sure how to set the path to: My Documents\test for example.
With the code I have, I get this error:
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Type error: Return value of Maatwebsite\Excel\Sheet::mapArraybleRow() must be of the type array, string returned
My Import class code:
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use App\Exports\TimesheetsExport;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Facades\Excel;
use App\User;
class TimesheetsImport implements ToCollection, WithHeadingRow
{
private $user;
public function __construct($param)
{
$this->user = $param;
}
public function collection(Collection $rows)
{
$data = new Collection([$this->user->fullName()]);
foreach ($rows as $row)
{
$data->put($row['date'], $row['in'], $row['out']);
}
return Excel::download(new TimesheetsExport($data), 'testtttt.xlsx');
My Export class:
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Support\Collection;
class TimesheetsExport implements FromCollection
{
protected $rows;
public function __construct(Collection $rows)
{
$this->rows = $rows;
}
public function collection()
{
return $this->rows;
}
}
Can someone please help?
After a day and a half, I managed to make it work.
The working code:
Import Class:
namespace App\Imports;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Facades\Excel;
use App\User;
class TimesheetsImport implements ToCollection, WithHeadingRow
{
public $data;
public function collection($rows)
{
$this->data = $rows;
}
}
Export class:
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
class TimesheetsExport implements FromCollection
{
protected $rows;
public function __construct($rows)
{
$this->rows = $rows;
}
public function collection()
{
return $this->rows;
}
}
My controller:
public function importTimesheets(Request $request)
{
$import = new TimesheetsImport;
$rows = Excel::toCollection($import, $request->file('file'));
return Excel::download(new TimesheetsExport($rows), 'test.xlsx');
}
With this code, I get the Windows 'Save File' as well.
This was not fun, but it's done, I hope it will help someone else.
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Excel;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Excel as ExcelType;
...
$array = [[1,2,3],[3,2,1]];
return \Excel::download(new class($array) implements FromArray{
public function __construct($array)
{
$this->array = $array;
}
public function array(): array
{
return $this->array;
}
},'db.xlsx', ExcelType::XLSX);
decided so without additional frames. Laravel 7*, Maatwebsite 3*
After trying to debug for a long time I run into an error of where I a variable does not seem to retrieve a value from the database.
Here is the code I use:
use App\Setting;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use View;
use DB;
class SettingsServiceProvider extends ServiceProvider
{
public function boot()
{
if(\DB::connection()->getDatabaseName() && Schema::hasTable('settings') && \DB::table('settings')->count()){
$setting = new Setting;
config()->set('website_desc', $setting->gets('general')->website_desc);
config()->set('website_keywords', $setting->gets('general')->website_keywords);
}
}
public function register()
{
// this approach worked before updating to 5.4
view()->share('website_desc',config('website_desc'));
view()->share('website_keywords',config('website_keywords'));
//does not work either
// View::share(['website_desc' => 'values', 'website_keywords' => 'values']);
}
}
my App/setting.php looks like this
namespace App;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $fillable = ['name','attributes'];
public function gets($name){
$attributes = $this->where('name',$name)->value('attributes');
if($attributes){
return json_decode($attributes);
}
return false;
}
}
Can anyone see anything that became incompatible?
This is the a database entry of the table settings and the column "attributes":
{"website_name":"name","website_title":"title","website_desc":"description","website_keywords":"keywords","website_footer_text":"footer"}
I am kind of at my wits end.