I want to upload a csv file into the database with laravel but it won't work properly. It get the message
Call to a member function prepare() on a non-object
inside my Controller.
Here is my CsvController
public function uploadCsv()
{
//We are going to insert some data into the users table
$sth = $dbh->prepare(
"INSERT INTO products (name, data_required_general, data_default_attribute, data_default_images)
VALUES (:name, :data_required_general, :data_default_attribute, data_default_images)"
);
$csv = Reader::createFromPath('/csvFile/test.csv');
$csv->setOffset(1); //because we don't want to insert the header
$nbInsert = $csv->each(function ($row) use (&$sth) {
//Do not forget to validate your data before inserting it in your database
$sth->bindValue(':name', $row[0], PDO::PARAM_STR);
$sth->bindValue(':data_required_general', $row[1], PDO::PARAM_STR);
$sth->bindValue(':data_default_attribute', $row[2], PDO::PARAM_STR);
$sth->bindValue(':data_default_images', $row[3], PDO::PARAM_STR);
return $sth->execute(); //if the function return false then the iteration will stop
});
}
My view
<div class="btn-group" role="group"> <!-- ~ btn btn-default btn-file ~ -->
Upload CSV
{{ Form::open(array('action' => 'CsvController@uploadCsv', 'method' => 'POST', 'class' => 'btn btn-default')) }}
{{ Form::file('file','',array('class' => 'form-control', 'accept' => '.csv')) }}
{{ Form::submit('Upload!', array('class' => 'btn btn-default')) }}
{{ Form::close() }}
</div>
And my Route
Route::post('csvUpload', array('as' => 'uploadCsv', 'uses' => 'CsvController@uploadCsv'));
From where do this $dbh object come from? This is not an object.
Solution: