I created my code following following few tutorials. As my csv file has more than 300k rows I need to upload it as chunks, but unable to figure out how to do that.
Mainly followed this tutorial and several others including some laracast discussions
https://itsolutionstuff.com/post/import-and-export-csv-file-in-laravel-58example.html
My Controller import function
public function import()
{
Excel::import(new ReportImport, request()->file('file'));
return view('dashboard');
}
My ReportImport File
namespace App\Imports;
use App\Report;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ReportImport implements ToModel, WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Report([
'district' => $row['district'],
'age' => $row['age'],
'email' => $row['email'],
'name' => $row['name'],
]);
}
}
Illuminate \ Http \ Exceptions \ PostTooLargeException
No message
Related
I'm an amateur front-end developer working on a web development project for my university. I'm going solo on this project have already finished the front-end part of the website. I used a temporary API to fetch the data that are passed on my views. Now, as I have to use a database, I build the database and I'm trying to fetch the data to my controllers. It is too complex for me, made almost zero progress so far. Making baby steps I'm now trying to fetch into a variable on my controller, JSON data containing all the table keys and values of a specific row. The response contains protected data and I have no idea how to fetch them the right way.
Any tip or advice would be much appreciated.
My test server's controller
<?php
namespace App\Http\Controllers;
use App\circuits;
use App\constructor_results;
use App\constructors;
use App\driver_standings;
use App\drivers;
use App\lap_times;
use App\pit_stops;
use App\qualifying;
use App\races;
use App\results;
use App\seasons;
use App\status;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$data = DB::table('circuits')
->select('circuits.*')
->where(['circuitId' => '6'])
->get();
print_r(response()->json($data));
}
}
The response (The wanted values are shown in the end of line)
Illuminate\Http\JsonResponse Object ( [data:protected] => [{"circuitId":"6","circuitRef":"monaco","name":"Circuit de Monaco","location":"Monte-Carlo","country":"Monaco","lat":"43.7347","lng":"7.42056","alt":"7","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_de_Monaco"}] [callback:protected] => [encodingOptions:protected] => 0 [headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object ( [computedCacheControl:protected] => Array ( [no-cache] => 1 [private] => 1 ) [cookies:protected] => Array ( ) [headerNames:protected] => Array ( [cache-control] => Cache-Control [date] => Date [content-type] => Content-Type ) [headers:protected] => Array ( [cache-control] => Array ( [0] => no-cache, private ) [date] => Array ( [0] => Tue, 09 Nov 2021 18:09:00 GMT ) [content-type] => Array ( [0] => application/json ) ) [cacheControl:protected] => Array ( ) ) [content:protected] => [{"circuitId":"6","circuitRef":"monaco","name":"Circuit de Monaco","location":"Monte-Carlo","country":"Monaco","lat":"43.7347","lng":"7.42056","alt":"7","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_de_Monaco"}] [version:protected] => 1.0 [statusCode:protected] => 200 [statusText:protected] => OK [charset:protected] => [original] => Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => stdClass Object ( [circuitId] => 6 [circuitRef] => monaco [name] => Circuit de Monaco [location] => Monte-Carlo [country] => Monaco [lat] => 43.7347 [lng] => 7.42056 [alt] => 7 [url] => http://en.wikipedia.org/wiki/Circuit_de_Monaco ) ) ) [exception] => )
Take a look at https://laravel.com/docs/8.x/eloquent-resources
(it should be valid for 5.8 as well https://laravel.com/docs/5.8/eloquent-resources, the idea is the same)
Of course, you may always convert Eloquent models or collections to
JSON using their toJson methods; however, Eloquent resources provide
more granular and robust control over the JSON serialization of your
models and their relationships.
So you can add a new Circuit Eloquent model, describe all fields and etc there, and add the toJson method, which will return array (there you can map what you want to return from the model).
I prefer to go with API Resources because in the feature you might need different responses in different places.
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CircuitResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
//add all fields which you want to return from the Circuit model
return [
'id' => $this->id,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
Then in the controller, you will use it like
use App\Http\Resources\CircuitResource;
use App\Models\Circuit;
...
return response()->json(new CircuitResource(Circuit::find(6)));
Model will be
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Circuit extends Model
{
/**
* The primary key associated with the table.
*
* #var string
*/
protected $primaryKey = 'circuitId';
}
To find 1 item it is better to use find() method. But if you search more than one, you will receive a Collection object. In that case, you will need to use the appropriate method on the created resource class, and from action, you should return
return response()->json(new CircuitResource::collection(Circuit::all()));
I'm trying to upload a file in yii2, the same code was working fine before but for some reason i can't figure out it stopped working after a lot of checks i notice the validate method of upload model is returning false and in the error message it says Array ( [file] => Array ( [0] => Only files with these extensions are allowed: png, jpg,jpeg,gif,pdf. ) ) but the most weird thing is i uploaded a jpg file i also try to upload a png file the same error, when i remove the check for extension in the model rules it works fineor totally remove the validation is also work, i don't know what am missing here any help would be appreciated.
NOTE //with the validation or the extension check for extension in place the codes in the if()
statement fails to execute but rather the else statement execute, removing the validation or the
extension check the code in if() works fine
class Upload extends Model
{
public $file;
public $randomCharacter;
public $fileDirectory;
public function rules()
{
return[
[['file'], 'file', 'skipOnEmpty' => false,'maxSize'=>1024 * 1024 * 2, 'extensions'=> ['png, jpg,jpeg,gif,pdf']],
];
}
public function upload($uploadPath=NULL)
{
if(isset($uploadPath) && $uploadPath !==NULL){
$filePath = $uploadPath;
}else{
$filePath = "#frontend/web/uploads/";
}
//generate random filename
$rand = Yii::$app->security->generateRandomString(10). '_' . time();
//assign generated file name to randomCharacter property
$this->randomCharacter = $rand;
//define the upload path;
if ($this->validate()){
$path = \Yii::getAlias($filePath);
$this->fileDirectory = $this->randomCharacter .'.'.$this->file->extension;
echo $path.$this->fileDirectory;
exit;
$this->file->saveAs($path.$this->fileDirectory );
return true;
}else{
// return false;
//with validation in place the else statement in executed
print_r($this->getErrors());
exit;
}
}
}
Remove the straight brackets of attribute "extensions"
Instead of:
[['file'], 'file', 'skipOnEmpty' => false,'maxSize'=>1024 * 1024 * 2, 'extensions'=> ['png, jpg,jpeg,gif,pdf']],
You should have this:
[['file'], 'file', 'skipOnEmpty' => false,'maxSize'=>1024 * 1024 * 2, 'extensions'=> 'png, jpg, jpeg, gif, pdf'],
I was looking for help creating an object of the type Illuminate\Http\Request. This article helped me understand the mechanism of the class, but I did not get the desired result.
Create a Laravel Request object on the fly
I'm editing the development code passed to me by the customer. The code has a function that gets a request parameter from vue and translates it to JSON:
$json = $request->json()->get('data');
$json['some_key'];
This code returned an empty array of data:
$json = $request->request->add([some data]);
or
$json = $request->request->replace([some data]);
this one returned an error for missing the add parameter
$json = $request->json->replace([some data]);
A variant was found by trying and errors. Maybe, it help someone save time:
public function index() {
$myRequest = new \Illuminate\Http\Request();
$myRequest->json()->replace(['data' => ['some_key' => $some_data]]);
$data = MyClass::getData($myRequest);
}
..
class MyClass extends ...
{
public static function getData(Request $request) {
$json = $request->json()->get('data');
$json['some_key'];
In addition, there are other fields in the class that you can also slip data into so that you can pass everything you want via Request
$myRequest->json()->replace(['data' => ['some_key' => $some_data]]);
..
$myRequest->request->replace(['data' => ['some_key' => $some_data]]);
..
$myRequest->attributes->replace(['data' => ['some_key' => $some_data]]);
..
$myRequest->query->replace(['data' => ['some_key' => $some_data]]);
$myRequest = new \Illuminate\Http\Request();
$myRequest->setMethod('POST');
$myRequest->request->add(['foo' => 'bar']);
dd($request->foo);
This from the link you shared works, give it a try. Thanks for sharing that link!
I am trying to run simple test and insert two record in db via fixture dataFile.
What I get is :
[ReflectionException] Class C:\xampp\htdocs\codeception\frontend\tests/_data\user.php does not exist
The file is obviously there. My UserTest.php looks like this:
<?php
class UserTest extends \Codeception\Test\Unit
{
public function _fixtures()
{
return [
'class' => \frontend\tests\fixtures\UserFixture::className(),
'dataFile' => codecept_data_dir() . 'user.php'
];
}
public function testValidation()
{
$user = new \common\models\User();
$user->setUsername(null);
$this->assertFalse($user->validate(['username']));
$user->setUsername('aaaaaaaaaaaaaaaaaaaaaaaaaa');
$this->assertFalse($user->validate(['username']));
$user->setUsername('toma');
$this->assertTrue($user->validate(['username']));
}
public function testIfUserExist()
{
$this->tester->seeRecord('user', ['name' => 'Toma']);
}
}
I saw the linux like forward slash in the error but don't know how to change it. Not sure if this is the problem because I had the same path with some images and it was fine then. What can cause this ? Thank you!
You're using seeRecord() in a wrong way. First argument needs to by class name, including namespace, so you should use it like this:
$this->tester->seeRecord(\frontend\models\User::class, ['name' => 'Toma']);
I spent half day to resolve this issue with no success.
I'm doing a setup in EC2, centos 6/64 bit. LAMP installed. On another hosting, my zf2 solution it work fine, so I've searched issue in php modules installed also (list at the end).
This error happen when zf2 try to get an instance of my custom service, also with wasabi mail.
\zend\config\application.config.php
'config_glob_paths' => array(
'./config/autoload/{,*.}{global,local}.php',
),
\zend\config\autoload\global.php
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
'Zend\CustomLogger' => function ($sm) {
$auth = $sm->get('zfcuser_auth_service');
$customLogger = new \Application\Service\CustomLogger(
$sm->get('Request'),
$sm->get('ZendLog'),
new \Zend\Session\SessionManager(),
$auth->getIdentity(), // $user
$sm->get('Mail'));
return $customLogger;
},
controller
<?php
namespace Foo\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Doctrine\ORM\EntityManager;
use MyProject\Proxies\__CG__\OtherProject\Proxies\__CG__\stdClass;
class FooController extends AbstractActionController
{
protected $customLogger;
private function getCustomLogger()
{
if (null === $this->customLogger) {
$this->customLogger = $this->getServiceLocator()->get('Zend\CustomLogger');
}
return $this->customLogger;
}
public function indexAction()
{
$this->getCustomLogger();
$this->customLogger->controllerLog("ENTER IN Foo\Controller\FooController\index", "info");
// .... other code
}
}
Error
Zend\ServiceManager\Exception\ServiceNotCreatedException
File:
/var/www/solutions/mysolution/zend/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:930
Message:
An exception was raised while creating "Zend\CustomLogger"; no instance returned
PHP modules installed
bz2.so curl.so fileinfo.so iconv.so mbstring.so mysqlnd.so pdo_sqlite.so shmop.so sqlite3.so sysvshm.so xmlreader.so xsl.so
calendar.so dom.so ftp.so intl.so mysqlnd_mysqli.so pdo_mysqlnd.so phar.so simplexml.so sysvmsg.so tokenizer.so xml.so zip.so
ctype.so exif.so gettext.so json.so mysqlnd_mysql.so pdo.so posix.so sockets.so sysvsem.so wddx.so xmlwriter.so
Extension enabled in PHP ini
extension=/usr/lib64/php/5.5/modules/php_bz2.so
extension=/usr/lib64/php/5.5/modules/php_curl.so
extension=/usr/lib64/php/5.5/modules/php_fileinfo.so
extension=/usr/lib64/php/5.5/modules/php_gd2.so
extension=/usr/lib64/php/5.5/modules/php_intl.so
extension=/usr/lib64/php/5.5/modules/php_mbstring.so
extension=/usr/lib64/php/5.5/modules/php_mysql.so
extension=/usr/lib64/php/5.5/modules/php_mysqli.so
extension=/usr/lib64/php/5.5/modules/php_openssl.so
extension=/usr/lib64/php/5.5/modules/php_pdo_mysql.so
extension=/usr/lib64/php/5.5/modules/php_soap.so
extension=/usr/lib64/php/5.5/modules/php_xmlrpc.so
extension=/usr/lib64/php/5.5/modules/php_xsl.so
So simple solution... permission on log directory and some others directory are wrong. Restore the correct permissione, user and group on directory (e.g. data/logs, data/cache...)