CodeIgniter 4 : no error but data won't insert to database - php

No error while I try to insert the data. in fact the session indicator shows that I successfully inserted the data, but when I check the database it was nothing.
public function save_agenda()
{
$idkelas = $this->request->getVar('id_kelas_loop');
$idtanggalkelasloop = $this->request->getVar('id_tanggal_kelas_loop');
$namakelas = $this->request->getVar('nama_kls');
$waktukelas = $this->request->getVar('waktu_kls');
$statuskelas = $this->request->getVar('status_kelas');
$tanggalkelas = array(
'id_tanggal_kelas' => $this->request->getVar('id_tanggal_kelas'),
'tanggal_kls' => $this->request->getVar('tanggal_kls')
);
$this->TanggalKelasModel->save($tanggalkelas);
for ($kls = 0; $kls < count($namakelas); $kls++) {
$this->KelasModel->save([
'id_kelas' => $idkelas[$kls],
'id_tanggal_kelas' => $idtanggalkelasloop[$kls],
'nama_kls' => $namakelas[$kls],
'waktu_kls' => $waktukelas[$kls],
'status_kls' => $statuskelas[$kls]
]);
}
session()->setFlashdata('sukses', 'Agenda berhasil diunggah');
return redirect()->to('/admin/admin/create_agenda');
}
This is my "KelasModel"
class KelasModel extends Model
{
protected $table = 'kelas';
protected $primaryKey = 'id_kelas';
protected $allowedFields = [
'id_kelas', 'id_tanggal_kelas', 'nama_kls', 'waktu_kls', 'status_kls'
];
}
class TanggalKelasModel extends Model
{
protected $table = 'tanggal_kelas';
protected $primaryKey = 'id_tanggal_kelas';
protected $allowedFields = [
'id_tanggal_kelas', 'tanggal_kls'
];
}
This is my "TanggalKelasModel"
<?php
namespace App\Models;
use CodeIgniter\Model;
class TanggalKelasModel extends Model
{
protected $table = 'tanggal_kelas';
protected $primaryKey = 'id_tanggal_kelas';
protected $allowedFields = [
'id_tanggal_kelas', 'tanggal_kls'
];
}
I have tried to check the allowed fields and the column names are the same.

Related

Codeigniter 4 ignoring model insert callback

Running model->insert() from my controller does not trigger the beforeInsert function, below is my model and the function from my conntroller
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model {
protected $table = 'admin_users';
protected $useAutoIncrement = true;
protected $primaryKey = 'row_uid';
protected $returnType = 'object';
protected $beforeInsert = ['passwordHash'];
protected $allowCallbacks = true;
protected $allowedFields = ['id', 'row_uid', 'username', 'email', 'password', 'active', 'deleted_at'];
public function __construct() {
return $this;
}
protected function passwordHash($data) {
$data['data']['row_uid'] = uniqid('',true);
$data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
if(isset($data['data']['password_c'])) unset($data['data']['password_c']);
return $data;
}
}
And here is the controller function
public function postRegister() {
$request = \Config\Services::request();
if($post = $request->getPost()) {
$valid = $this->validate([
'username' => 'is_unique[admin_users.username]', // Change table name to be dynamic
'email' => 'required|valid_email|is_unique[admin_users.email]', // Change table name to be dynamic
'password' => 'required|min_length[10]|max_length[100]',
'password_c' => 'required|matches[password]',
]);
if(!$valid) {
$this->data['errors'] = $this->validator->getErrors();
foreach($post as $key => $e) {
if(isset($this->data['errors'][$key])) {
$this->data['invalid_fields'][$key] = ' is-invalid';
} else $this->data['invalid_fields'][$key] = '';
}
return $this->getRegister();
}
$l = $this->userModel->insert($post);
echo '<pre>',var_dump($l),'</pre>';exit;
}
}
I determine that the callback is not running because the password is not hashed, the uid is not generated and running die or exit does nothing.
Thank you
EDIT:
I got it working by adding allowCallback() but i shouldn't need this?
$this->userModel->allowCallbacks(true)->insert($post);
1 - Delete the constructor method in the model; you don't need that .
2- set protected $allowCallbacks = true; before $beforeInsert = ['passwordHash'];
The above approach is standard coding in the Codeigniter framework. If those steps didnt resolve the problem, the solution is to check the database for the row_uid and password types.

Update hidden value after soft deleting in Laravel

I have four tables:
Agroindustria
Pessoa
PessoaJuridica
Endereco
. Here are their Models:
Agroindustria
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Agroindustria extends Model
{
use SoftDeletes;
protected $table = "agroindustria";
protected $primaryKey = "CodAgroindustria";
public $incrementing = false;
protected $keyType = 'string';
public $fillable = ['CodAgroindustria, Porte'];
public $hidden = ['created_at', 'updated_at', 'deleted_at'];
public function pessoa () {
return $this->setConnection('diana')->hasOne(Pessoa::class, 'CodPessoa', 'CodAgroindustria');
}
public function pessoajuridica()
{
return $this->setConnection('diana')->hasOne(PessoaJuridica::class, 'CodPessoa', 'CodEndereco');
}
public function endereco()
{
return $this->setConnection('diana')->hasOne(PessoaJuridica::class, 'CodEndereco', 'CodEndereco');
}
public function estado(){
return $this->setConnection('diana')->hasOne(Estado::class, 'CodEstado', 'estado');
}
public function cidade(){
return $this->setConnection('diana')->hasOne(Cidade::class, 'CodCidade', 'cidade');
}
}
Pessoa:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Pessoa extends Model
{
// use SoftDeletes;
protected $table = "pessoa";
protected $primaryKey = "CodPessoa";
public $incrementing = false;
protected $keyType = 'string';
protected $connection = "diana";
public $hidden = ['created_at', 'updated_at', 'EXCLUIDO', 'LastSend'];
public $fillable = ['email', 'TelRes', 'TelCel'];
public function endereco()
{
return $this->hasOne('App\Endereco', 'CodEndereco', 'CodEndereco');
}
public function pessoafisica()
{
return $this->hasOne('App\PessoaFisica', 'CodPessoaFisica', 'CodPessoa');
}
public function pessoajuridica()
{
return $this->hasOne('App\PessoaJuridica', 'CodPessoaJuridica', 'CodPessoa');
}
}
The PessoaJuridica and Endereco Models are pretty much the same as the Pessoa Model.
When I soft delete my Agroindustria, the deleted_at column updates successfully, but I'm struggling with updating the EXCLUIDO column values from 0 to 1 in my other models.
Here's the delete function I created in my AgroindustriaController:
public function deletar (Request $request)
{
try {
$Agroindustria = Agroindustria::where('CodAgroindustria', $request['CodAgroindustria']);
$Agroindustria->delete();
$Pessoa = Pessoa::findOrFail($request['CodPessoa']);
if ($Agroindustria->delete()) {
DB::table('Pessoa')->where('CodPessoa', $Pessoa->CodPessoa)
->update(array('EXCLUIDO' => 1));
}
return response()->json([
'error' => false,
'data' => [
'message' => 'Dados deletados com sucesso',
]
]);
} catch (Exception $e) {
return response()->json([
'error' => true,
'message' => [$e->getMessage()]
]);
}
}
second line in try
$Agroindustria->delete();
write this line like this
$dlt = $Agroindustria->delete();
after that in your if condition put this variable $dlt like this
if ($dlt) {
DB::table('Pessoa')->where('CodPessoa', $Pessoa->CodPessoa)
->update(array('EXCLUIDO' => 1));
}
Solved it by doing:
$Agroindustria = Agroindustria::where('CodAgroindustria', $request['CodAgroindustria']);
$dlt = $Agroindustria->delete();
if ($dlt) {
Pessoa::where('CodPessoa', $request['CodPessoa'])
->update(array('EXCLUIDO' => 1));
PessoaJuridica::where('CodPessoaJuridica', $request['CodPessoaJuridica'])
->update(array('EXCLUIDO' => 1));
Endereco::where('CodEndereco', $request['CodEndereco'])
->update(array('EXCLUIDO' => 1));
}
Thank you all!

how to get id of table in relationship to use in other table in this relation?

i have relation between Service and Services_Gallery one to many, and i want to use id of Service when i insert new image to Services_Gallery, and this is my Controller:
public function save(Request $request)
{
$this->validate($request,[
'image' => 'required|image|mimes:jpeg,jpg,png,svg|max:1024'
]);
$services_Gallery = new Services_Gallery();
$services_Gallery->image = $request->image->move('Uploads', str_random('6') . time() . $request->image->getClientOriginalName());
$services_Gallery->Service::all(id) = $request->service_id; //The problem here
$services_Gallery->save();
return back();
}
this is my Models:
class Service extends Model
{
protected $table = 'services';
protected $fillable = [
'en_main_title',
'ar_main_title',
'en_sub_title',
'ar_sub_title',
'en_content_title',
'ar_content_title',
'en_content',
'ar_content',
'priority',
];
public function gallery()
{
return $this->hasMany('App\Services_Gallery','service_id');
}
}
class Services_Gallery extends Model
{
protected $table = 'services_galleries';
protected $fillable = [
'image',
'service_id',
];
public function gallery(){
return $this->belongsTo('App\Service','service_id');
}
}
Exapmle:
$modelOfService = Service::where('param_x', $request->service_id)->first();
$id = $modelOfService->id;
Is that you need?

Laravel /ORM Doesnt create related table

How can I add value to a ORM related variable?
It contains a news and comments Model, as shown below:
class News extends Model {
protected $connection = 'mysql';
protected $primaryKey = 'id';
protected $table = 'news';
protected $fillable = array(
'id',
'name',
'category',
'type',
'datetime',
'shortdesc',
'desciption'
);
public $timestamps = false;
public function comments()
{
return $this->hasMany('App\Comments');
}
Comments table
class Comments extends Model {
protected $connection = 'mysql';
protected $primaryKey = 'id';
protected $table = 'comments';
protected $fillable = array(
'id',
'news_id',
'name',
'description'
);
public $timestamps = false;
public function news()
{
return $this->belongsTo('App\News','news_id');
}};
And when I try to add this values it creates only News table
without related Comments table.(Doesn't throw any exception, just creates News table)
public function AddData()
{
$row=new News;
$row->name="Myname";
$row->category="vcc";
$row->type="2";
$row->comments()->news_id="1";
$row->comments()->name="someval";
$row->save();
return view::make('first_view');
}
There is a problem when you are inserting your related Comment model. There are many ways to solve your problem.
Solution I prefer to use:
public function AddData()
{
// Create news model
$news = News::create([
'name' => 'Some name',
'category' => 'somecategory',
....
]);
// Create comment through news model
// news_id will automatically be inserted
$comment = $news->comments()->create([
'name' => 'some name'
]);
}
See documentation

Illuminate \ Database \ Eloquent \ ModelNotFoundException - No query results for model In laravel

I have the following data model
I am trying to get a have a Servicio given a Auth_Token of a Tecnico and id of a Servicio, but I get the following error appears
This is my code
Route
Route::post('servicio/download/{id}', array('uses' => 'ServicioController#pdf'));
Servicio model
class Servicio extends Eloquent{
protected $table = 'Servicio';
protected $fillable = array(
'RutaFoto1',
'RutaFoto2',
'RutaFoto3',
'RutaFoto4',
'FechaTermino',
'Latitud',
'Longitud'
);
protected $primaryKey = 'idServicio';
public function materialUsado(){
return $this->hasMany('Material_Usado', 'idMaterial_Usado');
}
public function tecnicos(){
return $this->belongsToMany('Tecnico', 'Servicio_Tecnico', 'Servicio_idServicio', 'Tecnico_idTecnico');
}
}
Tecnico Model
class Tecnico extends Eloquent{
protected $table = 'Tecnico';
protected $fillable = array('Auth_Token');
protected $primaryKey = 'idTecnico';
public function servicios(){
return $this->belongsToMany('Servicio', 'Servicio_Tecnico', 'Tecnico_idTecnico', 'Servicio_idServicio');
}
}
ServicioController
class ServicioController extends BaseController{
public function pdf($id){
$auth = Input::get('Auth_Token');
$tecnico = Tecnico::with('servicios')->where('Auth_Token',$auth)->firstOrFail();
if($tecnico != ''){
$servicios = $tecnico->servicios;
$servicio = $servicio->where('idServicio', $id)->first();
if($servicio != null){
$array = array(
'idServicio' => $servicio->idServicio,
'RutaPDF' => base64_encode($servicio->RutaPDF),
);
$response = Response::json($$array);
return $response;
}else{
$array = array('Error' => '', 'Code' => '');
return Response::json($array);
}
}else{
$array = array('Error' => 'NotAuthorizedError', 'Code' => '403', 'Message' => 'Tecnico inexistente');
$response = Response::json($array);
return $response;
}
}
}
how can I fix it?
You are using this:
$tecnico = Tecnico::with('servicios')->where('Auth_Token',$auth)->firstOrFail();
In this case, firstOrFail throws Illuminate\Database\Eloquent\ModelNotFoundException exception if it doesn't find the requested model and hence it could be because the model with that Auth_Token field is not available.
Make sure the Auth_Token is right and that Auth_Token is available in your database. You may try a dd(Input::get('Auth_Token')) to check what you have recieved from the POST submitted by the user.

Categories