image not save in data base (Laraval 8) - database

when I load an image via my form, the latter registers well in the / public storage but not in the database.
here is my recording function in ProduitController.
public function store(Request $request)
{
$request->validate([
'nom_produit' => 'required|min:4',
'prix_produit' => 'required|min:0.0',
'quantite_produit' => 'required|min:0.0',
'description_produit' => 'required|min:10',
'lieu_produit' => 'required|min:2',
'like_produit' => 'required|min:0.0',
'etat_produit' => 'required|min:0.0',
'vedette_produit' => 'required|min:0.0',
'user_id' => 'required|exists:users,id',
'categorie_id' => 'required|exists:categories,id',
'image_produit'=> 'mimes:jpeg,jpg,png,gif|required'
]);
$requestData = $request->all();
if ($request->hasfile('image_produit')) {
$image_produit = $request->file('image_produit');
$image_produit= $image_produit->getClientOriginalName();
//$path = $image_produit->storeAs('uploads\produit', $image_produit, 'public');
$path =$request->file('image_produit')->storeAs('uploads\produit', $image_produit, 'public');
}

after save the image in public folder then take a file name in variable
$file_name = uniqid().".".$request->file('image_produit')->getClientOriginalExtension();
and then save in the db.
Model::create(['image_produit' => $file_name]);

Related

Can't save data to database from input form - Laravel 8

it's me again. I have a problem saving data to the database from the input form that I made.
Here is my web route:
Route::get('/admin/data-karyawan', [BasicKaryawanController::class, 'data_karyawan']);
Route::get('/admin/create', [BasicKaryawanController::class, 'index']);
Route::post('/admin/create', [BasicKaryawanController::class, 'simpan']);
Here is my controller:
class BasicKaryawanController extends Controller
{
public function data_karyawan()
{
return view('data-karyawan', [
"title" => "Data Karyawan",
"karyawan" => Karyawan::with(['role', 'user'])->search(request(['search']))->paginate(10)
]);
}
public function index()
{
return view('create', [
"title" => "Tambah Karyawan"
]);
}
public function simpan(Request $request)
{
$validatedData = $request->validate([
'nik' => 'required|max:7',
'nama' => 'required|max:255',
'jk' => 'required|max:1',
'tempat_lahir' => 'required|max:255',
'tanggal_lahir' => 'required|max:255',
'alamat' => 'required|max:255',
'agama' => 'required',
'jabatan' => 'required|max:255',
'id_jabatan' => 'required|max:1',
'divisi' => 'required',
'email' => 'required|email:dns|unique:karyawans',
'password' => 'required|min:5|max:255'
]);
$validatedData['password'] = bcrypt($validatedData['password']);
Karyawan::create($validatedData);
return view('data-karyawan', [
"title" => "Data Karyawan",
"karyawan" => Karyawan::with(['role', 'user'])->search(request(['search']))->paginate(10)
]);
}
and this is my form blade view:
https://codeshare.io/3AzKD1
The code is running well but the form is not saving the data I input from the form to the database. Did I miss something?
Thank you.
This is solved.
I need to fill all the field on the table so it can store to the database.
Yes right, if u r using eloquent create method which accepts an array of attributes, creates a model, and inserts it into the database. The difference between save and create is that save accepts a full Eloquent model instance while create accepts a plain PHP array.
U can take the reference from here

How to access data from a query to a CGridView

I'm trying to use on my view a search made by CreateCommand to fill my CGridView, but I still need to pass as a dataProvider a CActiveDataProvider object.
Is there any way to transform my CreateCommand object into CActiveDataProvider or to do the same query directly as a CActiveDataProvider?
This is the view
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'credenciado-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'afterAjaxUpdate' => "loadAfterAjax",
'rowHtmlOptionsExpression' => 'array("style"=>"cursor: pointer","data-row-id" => $data->cre_id, "class" => "row_grid")',
'columns' => array(
'cre_razao_social',
array(
'header'=>'Status',
'name'=>'cre_ativo',
'value'=>'Status::getStatus($data->cre_ativo)',
'filter'=>array(true => 'ATIVO',false => 'INATIVO'),
'filterHtmlOptions'=>array('class'=>'col-sm-2'),
),
),
)); ?>
This is the controller
$model = new Credenciado('getValoresCredenciadosByConvenioRank');
$model = new CArrayDataProvider($model, array());
// pe($model);
$modelEst = new Estabelecimento('search_adm');
// pe($model);
$modelEst->unsetAttributes();
if (isset($_GET['Estabelecimento']))
$modelEst->setAttributes($_GET['Estabelecimento']);
// $model->unsetAttributes();
// if (isset($_GET['Credenciado']))
// $model->setAttributes($_GET['Credenciado']);
$this->render('listar',array(
'model' => $model,
'modelEst' => $modelEst,
'mes1' => $mes1,
'mes2' => $mes2,
'meses' => $meses,
'produto' => $produto,
'data' => $format,
'datas' => $date_unique,
'series' => $series,
'ano1' => $ano1,
'ano2' => $ano2
));
}
This is the Model
$q = Yii::app()->db->createCommand()
->select("
cre.cre_razao_social,
count(op.ope_id) as linhas,
par.par_data_vencimento,
pro.pro_codigo,
SUM(
CASE
WHEN date_trunc('month',par_data_vencimento) < date_trunc('month',now()) AND pro_codigo != 2 THEN
par.par_valor
WHEN pro_codigo = 2 THEN
op.ope_valor_parcela
ELSE
op.ope_valor_parcela
END
) as total_carteira")
->from("operacao op")
->join('parcela par', 'par.par_operacao_ope_id = op.ope_id')
->join('pos po', 'po.pos_id = op.ope_pos_pos_id')
->join('rubrica_credenciado rub', 'rub.rub_id = po.pos_rubrica_credenciado_rub_id')
->join('credenciado cre','rub.rub_credenciado_cre_id = cre_id')
->join('produto pro', 'pro.pro_id = rub.rub_produto_pro_id')
->join('matricula ma', 'ma.mat_matricula = op.ope_matricula AND ma.mat_convenio_con_id = '.Yii::app()->user->convenioid.' ')
->where('op.ope_con_id = :con_id', array(':con_id' => $con_id));
$q->andWhere(
"(par.par_data_vencimento between :datamin and :datamax and ope_status in('E','S'))
OR
(par.par_data_vencimento between :datamin and :datamax AND par.par_num_parcela = op.ope_qtde_parcelas AND op.ope_status = 'Q')
",
array(':datamin'=>$datamin, ':datamax'=>$datamax));
if(Yii::app()->user->sistema != 1) {
$q->andWhere('rub_consignavel = true');
}
$q->order('par.par_data_vencimento', 'ASC');
//$q->andWhere(array('in', 'ope_status', array('E','S')));
$q->group('cre.cre_razao_social, pro.pro_codigo, par.par_data_vencimento');
$q->queryAll();
This is the error
exception 'CException' with message 'CArrayDataProvider and its behaviors
do not have a method or closure named "search".' in
/var/www/html/yii/framework/base/CComponent.php:266
Stack trace:
you are making a mistake in your view. In your controller you are already passing object of CArrayDataProvider (i.e $model) to your view, so you should not call search() function on $model variable. Instead you should create CArrayDataProvider object from CreateCommand in your model and pass the object of Credenciado as $model in your controller and call your query method in the view like $model-> getValoresCredenciadosByConvenioRank() to get the data provider. Then your view would look like this
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'credenciado-grid',
// call your query function to get data provider (this is the name of function that you have implemented in your model)
'dataProvider' => $model->getValoresCredenciadosByConvenioRank(),
'filter' => $model,
'afterAjaxUpdate' => "loadAfterAjax",
'rowHtmlOptionsExpression' => 'array("style"=>"cursor: pointer","data-row-id" => $data->cre_id, "class" => "row_grid")',
'columns' => array(
'cre_razao_social',
array(
'header'=>'Status',
'name'=>'cre_ativo',
'value'=>'Status::getStatus($data["cre_ativo"])',
'filter'=>array(true => 'ATIVO',false => 'INATIVO'),
'filterHtmlOptions'=>array('class'=>'col-sm-2'),
),
),
));
?>
Your controller would become this
$model = new Credenciado('getValoresCredenciadosByConvenioRank');
$model->unsetAttributes();
if (isset($_GET['Credenciado']))
$model->setAttributes($_GET['Credenciado']);
// pe($model);
$modelEst = new Estabelecimento('search_adm');
// pe($model);
$modelEst->unsetAttributes();
if (isset($_GET['Estabelecimento']))
$modelEst->setAttributes($_GET['Estabelecimento']);
$this->render('listar',array(
'model' => $model,
'modelEst' => $modelEst,
'mes1' => $mes1,
'mes2' => $mes2,
'meses' => $meses,
'produto' => $produto,
'data' => $format,
'datas' => $date_unique,
'series' => $series,
'ano1' => $ano1,
'ano2' => $ano2
));
}
And your model would return CArrayDataProvider instead of query result like this,
$queryResult = $q->queryAll();
// return data provider for view instead of query result
return new CArrayDataProvider($queryResult, array());
Hopefully this solution will solve your problem. Let me know if it works or if the problem still persists.

Laravel 5: add data to $request->all()

I've been trying to add the id of the current logged-in user into a field in my DB.
But, nothing is stored. I have tried the following methods:
public function store(StoreChildRequest $request)
{
$user = Auth::user();
$child = $request->all();
$child->merge(['user_id' => $user->id]);
$child = new Patient($child);
$child->save();
}
But the StoreChildRequest always returns the user_id is not passed.
Also this didn't work:
public function store(StoreChildRequest $request)
{
$user = Auth::user();
Input::merge(['user_id' => $user->id]);
$child = new Patient($request->all());
$child->save();
}
The same error.
Even if I try to do so with fixed data, the merge won't happen:
public function store(StoreChildRequest $request)
{
$user = Auth::user();
Input::merge(['user_id' => "01"]);
if($child = new Patient($request->all()))
{
$child->save();
return response()->json(['succes' => 'Child saved.']);
}
else
{
return response()
->json($request->getMessageBag()->toArray());
}
}
EDIT
I have noticed that when I remove the StoreChildRequest (the validation) the code works just fine. So I'm going to add the rules:
StoreChildRequest:
public function rules()
{
return [
'name' => 'required|max:255',
'givenname' => 'required|max:255',
'street' => 'required|max:255',
'streetnumber' => 'required|max:255',
'city' => 'required|max:255',
'postalcode' => 'required|digits:4',
'email' => 'required|email',
'birthdate' => 'required|date',
'sex' => 'required|max:1',
'user_id' => 'required'
];
}
The error has to be in here then?
Thank you for your help.
You could do something like this:
$user = Auth::user();
$child = $request->all();
$child['user_id'] = $user->id;
$child = new Patient($child);
$child->save();
Also, you could try:
$user = Auth::user();
$request->request->add(['user_id' => $user->id]);
$child = $request->all();
$child = new Patient($child);
$child->save();

Can't get uploading in zf2 working. File is always not valid?

Im am trying to create a controller that uploads a file for me but I always get the same result. The file isn't valid so he doesn't upload.
The function in my controller is:
$upload = new \Zend\File\Transfer\Transfer();
$upload->setDestination('./data/images/uploads/');
$rtn = array('success' => null);
if ($this->getRequest()->isPost()) {
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
if (!$upload->isUploaded($file)) {
print "<h3>Not Uploaded</h3>";
\Zend\Debug\Debug::dump($file);
continue;
}
if (!$upload->isValid($file)) {
print "<h4>Not Valid</h4>";
\Zend\Debug\Debug::dump($file);
continue;
}
}
$rtn['success'] = $upload->receive();
}
return new \Zend\View\Model\JsonModel($rtn);
The result is:
<h4>Not Valid</h4><pre>string(8) "files_0_"
</pre>{"success":false}
When I look at $files (print_r()) I get:
Array
(
[files_0_] => Array
(
[name] => logo_welcome.gif
[type] => image/gif
[tmp_name] => /private/var/tmp/phpiufvIc
[error] => 0
[size] => 62935
[options] => Array
(
[ignoreNoFile] =>
[useByteString] => 1
[magicFile] =>
[detectInfos] => 1
)
[validated] =>
[received] =>
[filtered] =>
[validators] => Array
(
[0] => Zend\Validator\File\Upload
)
[destination] => ./data/images/uploads
)
)
As you can see in ZF2 docs, file uploading with Zend\File\Transfer has been deprecated in favor of using the standard ZF2 Zend\Form and Zend\InputFilter features.
Having said that, you should use Zend\Filter\File\RenameUpload to move the uploaded file. You just need to attach the Zend\Filter\File\RenameUpload filter to your InputFilter specification, like that:
$this->add([
'name' => 'file',
'type' => 'Zend\InputFilter\FileInput',
'filters' => [
[
'name' => 'FileRenameUpload',
'options' => [
'target' => realpath('./data/uploads/'),
'randomize' => true,
'use_upload_extension' => true,
],
],
],
]);
And in your controller action:
if ($this->request->isPost()) {
$post = array_merge_recursive(
$this->request->getPost()->toArray(),
$this->request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid()) {
// File uploaded and moved to data/uploads folder
}
}
Take a look in official documentation for a complete example.

ConnectionManager getDataSource undefined method

Using cakephp 2.3.8 I am attempting to setup a connection to a custom couchbase datasource I have made within another datasource. The datasource I am attempting to load functions properly on the rest of the site when being loaded via a model. I want to use the connection manager to load this datasource. This is what I have so far:
database.php file:
public $queriesCB = array(
'datasource' => 'CouchbaseSource',
'username' => 'queries',
'password' => '',
'bucket' => 'queries',
'prefix' => 'q_',
'expiry' => '1814400', //3 Weeks
'autoConnect' => true,
'database' => NULL ,
'persistent' => false
);
Within my other datasource trying to load couchbase datasource
$db = ConnectionManager::getDataSource("queriesCB");
When I debug $db I get this:
object(CouchbaseSource) {
description => 'Couchbase DataSource'
conObject => object(Couchbase) {
[private] _handle => resource
}
config => array(
'password' => '*****',
'database' => '*****',
'prefix' => '*****',
'datasource' => 'CouchbaseSource',
'username' => 'queries',
'bucket' => 'queries',
'expiry' => '1814400',
'autoConnect' => true,
'persistent' => false
)
prefix => 'q__'
connected => false
cacheSources => true
configKeyName => 'queriesCB'
[protected] _baseConfig => array()
[protected] _descriptions => array()
[protected] _sources => null
[protected] _transactionStarted => false
}
Now when I try to call this I get a error:
$db = ConnectionManager::getDataSource("queriesCB");
$db->Get('test');
Error: Call to undefined method CouchbaseSource::Get().
This is a custom method, the datasource is all custom to work best with couchbase and the Get method does function properly. How am I setting up this connection wrong in cakephp?
Edit:
I just tested it with the default database config to a mysql database, it fails as well. The question now would be what would be the best way to initialize a new datasource? should I have to load a model with that datasource attached? Example: have a couchbase model with the datasource as couchbase?
Edit: Here is some of the datasource
class CouchbaseSource extends DataSource {
public $description = 'Couchbase DataSource';
public $conObject = NULL;
public $config = NULL;
public $prefix = NULL;
public function __construct($config = array()){
// If no configuration is set we use the default
$this->config = $config;
// Setup the cache string that is used when building the string
$this->prefix = (isset($this->config['prefix']) ? $this->config['prefix']."_" : "");
if ($this->config['autoConnect']) {
$this->connect();
}
}
public function connect() {
if ($this->conObject !== true) {
try {
$this->conObject = new Couchbase("127.0.0.1:8091", $this->config['username'], $this->config['password'], $this->config['bucket'], $this->config['persistent']);
} catch (Exception $e) {
throw new MissingConnectionException(array('class' => $e->getMessage()));
}
}
return $this->conObject;
}
public function query($method, $params, $object) {
// If not connected... reconnect!
if(!$this->conObject) {
$this->connect();
}
$apiMethod = $this->__methodToClass($method);
if (!method_exists($this, $apiMethod)) {
throw new NotFoundException("Class '{$apiMethod}' was not found");
} else {
return call_user_func_array(array($this, $apiMethod), $params);
}
}
private function __methodToClass($method) {
return 'CB' . strtolower(Inflector::camelize($method));
}
public function describe(&$Model) {
return $this->description;
}
/////////////////////////////////////////////////
// Query Methods
/////////////////////////////////////////////////
public function CBadd($key = NULL, $value = NULL, $expiry = NULL, $persisto = NULL, $replicateto = NULL) {
return $this->conObject->add($key, $value, $expiry, $persisto, $replicateto);
}
The solution is to directly call the query method from the couchbasesource. Given the way that I setup the datasource, unlike linking it through a model, the query information was not automatically passed. My go around was to simple use this.
App::uses('ConnectionManager', 'Model');
$db = ConnectionManager::getDataSource("queriesCB");
debug($db->query('Get', array('test')));

Resources