laravel 5 issue with slashes in query - laravel-5

I am using Laravel 5 and I am facing issues with query when I have slashes(forward or backward)
publications table structure:
CREATE TABLE IF NOT EXISTS `publications` (
`id` bigint(20) NOT NULL,
`user_id` bigint(20) NOT NULL,
`title` varchar(512) NOT NULL,
`type` varchar(512) NOT NULL,
`company` varchar(512) NOT NULL,
`author` varchar(512) NOT NULL,
`firm` varchar(512) NOT NULL,
`address` text NOT NULL,
`sector_id` bigint(20) NOT NULL DEFAULT '0',
`date_from` timestamp NULL DEFAULT NULL,
`date_to` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`region_id` bigint(20) NOT NULL DEFAULT '0',
`file_name` varchar(512) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` bigint(20) NOT NULL,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_by` bigint(20) NOT NULL,
`is_active` tinyint(1) NOT NULL DEFAULT '1',
`category_id` bigint(20) NOT NULL,
`sub_category_id` bigint(20) NOT NULL,
`manually_verified` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
Data:
INSERT INTO `publications` (`id`, `user_id`, `title`, `type`, `company`, `author`, `firm`, `address`, `sector_id`, `date_from`, `date_to`, `region_id`, `file_name`, `created_at`, `created_by`, `updated_at`, `updated_by`, `is_active`, `category_id`, `sub_category_id`, `manually_verified`) VALUES
(3, 7, 'test publication 3', 'test 1', 'test 1', 'test author 1', 'test 1', 'test3', 1, '2015-06-09 11:54:18', '2015-06-29 18:30:00', 0, 'files/testing/testing.pdf', '2015-06-06 05:58:10', 7, '2015-06-13 03:31:45', 7, 0, 4, 1, 0),
(4, 7, 'test publication 4', 'test 2', 'test 2', 'test author 2', 'test 2', 'test2', 1, '2015-06-09 11:54:23', '2015-06-29 18:30:00', 0, 'test1.pdf', '2015-06-06 05:58:10', 7, '2015-06-05 23:58:10', 7, 1, 4, 1, 0),
(5, 7, 'test 5', 'test', 'test', 'test', 'test', 'test', 1, '2015-06-09 11:54:09', '2015-06-29 18:30:00', 0, 'files/Bugzilla-uermanual.pdf', '2015-06-06 05:58:10', 7, '2015-06-13 03:19:21', 7, 0, 4, 1, 1);
Laravel 5
$arr = array( 'file_paths' => Array ( 'files/testing/testing.pdf', 'files/Bugzilla-uermanual.pdf' ) );
Query
$this->publications
->where(['category_id'=>$search_cat_id])
->where(function ($query) use ($arr){
foreach ($arr['file_paths'] as $key=>$value){
$query->orWhere('file_name', DB::connection()->getPdo()->quote($value));
}
})
->get();
print_r($publications_records);
I don't get any result. If I execute the query which was generated by laravel it is getting executed.
Below is the query generated by Laravel and if I execute this in MySQL I get results.
select * from `publications`
where (`category_id` = 4) and
(`file_name` = 'files/testing/testing.pdf'
or `file_name` = 'files/Bugzilla-uermanual.pdf')
order by `id` desc

Try this:
$arr = ['files/testing/testing.pdf', 'files/Bugzilla-uermanual.pdf'];
$publications_records = $this->publications()
->where('category_id', $search_cat_id)
->where(function ($query) use ($arr){
foreach ($arr as $value){
$query->orWhere('file_name', $value);
}
})
->get();
dd($publications_records, DB:getQueryLog());
If the above code doesnt work. Please edit your question and paste the output

Related

CakePHP 4.x : How to create a set of form controls that list all of the values in a HABTM (through) association?

I'm trying to create single edit form based on contacts that allows me to update/add skill levels for all the skills even if the contact doesn't already have a rating.
Something like:
Edit Contact
Name [TextBox: John Doe]
Skills
C# [TextBox: empty]
C/C++ [TextBox: empty]
Data Analysis [TextBox: 5]
Graphic Design [TextBox: empty]
Javascript [TextBox: 8]
Photography [TextBox: empty]
HTML [TextBox: empty]
Json [TextBox: empty]
Jquery [TextBox: empty]
My tables are configured like this:
Contacts
TABLE `contacts` (
`id` bigint(20) NOT NULL,
`name` varchar(100) NOT NULL
)
(1, 'John Doe')
$this->belongsToMany('Skills', [
'foreignKey' => 'contact_id',
'targetForeignKey' => 'skill_id',
'joinTable' => 'contacts_skills', (Tried with and without)
'through' => 'ContactsSkills', (Tried with and without)
]);
Skills
TABLE `skills` (
`id` bigint(20) NOT NULL,
`name` text NOT NULL
)
(1,'C#'),
(2,'C/C++'),
(3,'Data Analysis'),
(4,'Graphic Design'),
(5,'Javascript'),
(6,'Photography'),
(7,'HTML'),
(8,'Json'),
(9,'Jquery')
$this->belongsToMany('Contacts', [
'foreignKey' => 'skill_id',
'targetForeignKey' => 'contact_id',
'joinTable' => 'contacts_skills', (Tried with and without)
'through' => 'ContactsSkills', (Tried with and without)
]);
ContactsSkills
TABLE `contacts_skills` (
`id` bigint(20) NOT NULL,
`contact_id` bigint(20) NOT NULL,
`skill_id` bigint(20) NOT NULL,
`level` tinyint(1) DEFAULT NULL
)
(1,1,3,5),
(2,1,5,8)
$this->belongsTo('Contacts', [
'foreignKey' => 'contact_id',
'joinType' => 'INNER',
]);
$this->belongsTo('Skills', [
'foreignKey' => 'skill_id',
'joinType' => 'INNER',
]);
I've already dug though the documentation:
https://book.cakephp.org/4/en/orm/saving-data.html
https://book.cakephp.org/4/en/views/helpers/form.html (where I learned about _joinData) NOTE: The multiple select element doesn't
work for _joinData.
And many more. : )
I've tried just about every combination of associations to connect the three tables together, to no avail.
I know I can use _joinData to get the skills that already have a level:
echo $this->Form->control('skills.0._joinData.level');
echo $this->Form->control('skills.1._joinData.level', ['label' => ?????]);
though I'm having issues setting the label to the skill name.
My assumption is that I have to iterate the skills table and build the controls that way, but I don't know how to reference the join table from within the iteration.
Any suggestions?

Unable to resolve NULL driver for [Maatwebsite\Excel\Transactions\TransactionManager]

I am trying to download data from database to excel file. I have import the Maatwebsite\Excel from composer also.
my code in my controller is:
function excel()
{
$month = date('m');
DB::statement("CREATE OR REPLACE VIEW monthly_cost AS
select user_name, id, phone, sum(cost) as cost from (
select users.name as user_name, users.roll as id,users.phone as phone, BC.individual_cost as cost
from breakfast_orders BO, breakfast_costs BC,users
WHERE (BO.date=BC.date) and (BO.user_id=users.id)and MONTH(BO.date)='$month'
UNION ALL
select users.name as user_name, users.roll as id,users.phone as phone, LC.individual_cost as cost
from lunch_orders LO, lunch_costs LC,users
WHERE (LO.date=LC.date) and (LO.user_id=users.id) and MONTH(LO.date)='$month'
UNION ALL
select users.name as user_name, users.roll as id,users.phone as phone, DC.individual_cost as cost
from dinner_orders ddO, dinner_costs DC,users
WHERE (ddO.date=DC.date) and (ddO.user_id=users.id) and MONTH(ddO.date)='$month'
) x group by id,user_name,phone");
$customer_data=DB::table('monthly_cost')->get()->toArray();
$customer_array[] = array('Name', 'ID', 'Phone', 'Cost', 'Month');
foreach($customer_data as $customer)
{
$customer_array[] = array(
'Name' => $customer->user_name,
'ID' => $customer->id,
'Phone' => $customer->phone,
'Cost' => $customer->cost,
'Month' => $month
);
}
Excel::create('Customer Data', function($excel) use ($customer_array){
$excel->setTitle('Customer Data');
$excel->sheet('Customer Data', function($sheet) use ($customer_array){
$sheet->fromArray($customer_array, null, 'A1', false, false);
});
})->download('xlsx');
}
what should I do now?
Just run php artisan config:clear or php artisan config:cache.

Laravel 5.8: Error Field doesn't have a default value

I saw similar questions but non of them work for me. This is the Transition model
class Transition extends Model
{
protected $fillable = ['origin_x', 'origin_y', 'destination_x', 'destination_y', 'freight_id', 'status', 'receiver_name', 'receiver_mobile', 'receiver_address'];
protected $table = 'freight_transitions';
}
and this is the insertion code
$transition = Transition::create([
'origin_x' => $redis['origin_x'],
'origin_y' => $redis['origin_y'],
'destination_x' => $redis['destination_x'],
'destination_y' => $redis['destination_y'],
'freight_id' => $freight->id,
'status' => 2,
'receiver_name' => $redis['receiver_name'],
'receiver_mobile' => $redis['receiver_mobile'],
'receiver_address' => $redis['receiver_address']
]);
I am sure the array of $redis` has value. But this is the error
General error: 1364 Field 'origin_x' doesn't have a default value (SQL: insert into freight_transitions (updated_at, created_at) values (2019-11-02 16:42:58, 2019-11-02 16:42:58))
From what I see, the Laravel does not try to insert the origin_x and other fields in to the DB. it only inserts the created_at and updated_at. I have a similar model called Freight, in a few lines above this code, I insert records in the same way with no error. But I don't know why it only inserts the created_at and updated_at.
I also tried
$transition = new Transition([....]);//array of above data
$transition->save();
It also generates the same error.
This is the migration
Schema::create('freight_transitions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('origin_x');
$table->string('origin_y');
$table->string('destination_x');
$table->string('destination_y');
$table->string('receiver_name')->nullable();
$table->string('receiver_mobile')->nullable();
$table->string('receiver_address')->nullable();
$table->bigInteger('freight_id')->unsigned();
$table->foreign('freight_id')->references('id')->on('freight_freights')->onDelete('cascade');
$table->enum('status', ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14'])->default(1);//1: start
$table->timestamps();
});
and this is redis array in json format
{
"origin_x": "555",
"origin_y": "666",
"destination_x": "777",
"destination_y": "8888",
"freight_type_id": "1",
"title": null,
"description": null,
"price": 130000,
"features": "2",
"services": "2,5",
"vehicle_id": 1,
"token": "111111",
"payment_type": "3",
"user_id": 1,
"receiver_name": null,
"receiver_mobile": null,
"receiver_address": null,
"payment_status": 1,
"status": 2
}
Thanks in advance.
I tried to insert data as follows
$transition = new Transition;
$transition ->origin_x = $redis['origin_x'];
$transition ->origin_y = $redis['origin_y'];
$transition ->destination_x = $redis['destination_x'];
$transition ->destination_y = $redis['destination_y'];
$transition ->freight_id = $freight->id;
$transition ->status = 2;
$transition ->receiver_name = $redis['receiver_name'];
$transition ->receiver_mobile = $redis['receiver_mobile'];
$transition ->receiver_address = $redis['receiver_address'];
$transition->save();
Even though it works, but it is still a question to me why the codes I use for tons of projects doesn't work here :|
Did you convert your json into array if not convert it into array using json_decode function of php and try again. if possible then give default value to your columns.

Laravel unique field validate not working

i have have a field called mac where i store mac address but i need it to be unique to avoid duplicate mac address.
code:
return [
'user_id' => 'required|integer',
'mac' => array('required|unique:mac', 'regex:/^([0-9A-Z]{2}[-]){5}([0-9A-Z]{1,2})$/'),
];
error:
Method [validateRequired|unique] does not exist.
structure:
CREATE TABLE `devices` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`mac` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`content` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `devices_mac_unique` (`mac`),
KEY `devices_user_id_foreign` (`user_id`),
CONSTRAINT `devices_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
You would need to define the table the mac address would need to be checked against
return [
'user_id' => 'required|integer',
'mac' => 'required|unique:devices,mac|regex:/^([0-9A-Z]{2}[-]){5}([0-9A-Z]{1,2})$/',
];
Update - When updating the record, instead of a create you would extend your rule to.
return [
'user_id' => 'required|integer',
'mac' => 'required|unique:devices,mac,' . $device->id . '|regex:/^([0-9A-Z]{2}[-]){5}([0-9A-Z]{1,2})$/',
];

CodeIgniter: Unknown column 'xxx' in 'field list'

Here's my exported BD table:
CREATE TABLE `hta_users` (
`id` int(11) NOT NULL auto_increment,
`nombre` varchar(100) collate utf8_spanish_ci NOT NULL,
`apellidos` varchar(255) collate utf8_spanish_ci NOT NULL,
`nif` varchar(10) collate utf8_spanish_ci NOT NULL,
`direccion` varchar(255) collate utf8_spanish_ci NOT NULL,
`cp` varchar(5) collate utf8_spanish_ci NOT NULL,
`poblacion` varchar(255) collate utf8_spanish_ci NOT NULL,
`provincia` int(2) NOT NULL,
`telefono` varchar(9) collate utf8_spanish_ci NOT NULL,
`edad` int(3) NOT NULL,
`retribucion` int(1) NOT NULL,
`entidad` varchar(4) collate utf8_spanish_ci NOT NULL,
`oficina` varchar(4) collate utf8_spanish_ci NOT NULL,
`dc` varchar(2) collate utf8_spanish_ci NOT NULL,
`cc` varchar(10) collate utf8_spanish_ci NOT NULL,
`centro` varchar(255) collate utf8_spanish_ci NOT NULL,
`email` varchar(255) collate utf8_spanish_ci NOT NULL,
`especialidad` int(2) NOT NULL,
`parent` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `nif` (`nif`,`email`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci AUTO_INCREMENT=1 ;
Here's my model function:
function add_user( $nombre, $apellidos, $nif, $direccion, $cp, $poblacion, $provincia, $telefono, $edad, $retribucion, $cc_entidad, $cc_oficina, $cc_dc, $cc_cc, $centro, $email, $especialidad, $parent )
{
$tbl = $this->db->dbprefix('users');
if( $retribucion == 1 )
{
$sql = array(
'nombre' => $nombre,
'apellidos' => $apellidos,
'nif' => $nif,
'direccion' => $this->db->escape($direccion),
'cp' => $cp,
'poblacion' => $poblacion,
'provincia' => $provincia,
'telefono' => $telefono,
'edad' => $edad,
'retribucion' => $retribucion,
'entidad' => $cc_entidad,
'oficina' => $cc_oficina,
'dc' => $cc_dc,
'cc' => $cc_cc,
'centro' => $centro,
'email' => $email,
'especialidad' => $especialidad,
'parent' => $parent
);
}
else
{
$sql = array(
'nombre' => $nombre,
'apellidos' => $apellidos,
'nif' => $nif,
'direccion' => $this->db->escape($direccion),
'cp' => $cp,
'poblacion' => $poblacion,
'provincia' => $provincia,
'telefono' => $telefono,
'edad' => $edad,
'retribucion' => $retribucion,
'centro' => $centro,
'email' => $email,
'especialidad' => $especialidad,
'parent' => $parent
);
}
$this->db->insert($tbl, $sql);
if( $this->db->affected_rows() == 0 ) return false;
else return true;
}
Here's my controller piece of code:
if( $this->users->add_user($nombre, $apellidos, $nif, $direccion, $cp, $poblacion, $provincia, $telefono, $edad, $retribucion, $cc_entidad, $cc_oficina, $cc_dc, $cc_cc, $centro, $email, $especialidad, $parent) )
{
$data['form_error'] = 'Se ha aƱadido al usuario.';
$data['module'] = 'registro';
$this->load->view('template', $data);
}
else
{
$data['form_error'] = 'Se ha producido un error al agregar al usuario a la BD.';
$data['module'] = 'registro';
$this->load->view('template', $data);
}
And that's the error i'm getting:
A Database Error Occurred
Error Number: 1054
Unknown column 'entidad' in 'field list'
INSERT INTO `hta_users` (`nombre`, `apellidos`, `nif`, `direccion`, `cp`, `poblacion`, `provincia`, `telefono`, `edad`, `retribucion`, `entidad`, `oficina`, `dc`, `cc`, `centro`, `email`, `especialidad`, `parent`) VALUES ('nombre', 'apellidos', '12345678Q', '\'elm st 666\'', '08008', 'Barcelona', '1', '666555666', '2', 1, '9999', '9999', '99', '9999999999', 'home', 'email#domain.com', '1', '0')
Can someone help? I don't know what's happening nor why... :/
Here is an article I wrote that will help you with debugging CodeIgniter ActiveRecord. Basically use $this->db->last_query() to see what ActiveRecord built your query to be and run it in phpMyAdmin to see if the query itself is valid.
There are a few other tips too, but from what I can see here everything looks fine.
Sneaky tip: you can use:
return !$this->db->affected_rows() == 0;
instead of:
if( $this->db->affected_rows() == 0 ) return false;
else return true;
Well, after some hours of harddebuggin' got it working... :P
Same database table structure.
My new model function:
function add_user( $user_data )
{
$tbl = $this->db->dbprefix('users');
$this->db->insert($tbl, $user_data);
return !$this->db->affected_rows() == 0;
}
My new controller piece of code:
$user_data = array(
'nombre' => $this->input->post('nombre'),
'apellidos' => $this->input->post('apellidos'),
'nif' => $this->input->post('nif'),
'direccion' => $this->db->escape($this->input->post('direccion')),
'cp' => $this->input->post('cp'),
'poblacion' => $this->input->post('poblacion'),
'provincia' => $this->input->post('provincia'),
'telefono' => $this->input->post('telefono'),
'edad' => $this->input->post('edad'),
'retribucion' => $this->input->post('retribucion'),
'entidad' => $this->input->post('cc_entidad'),
'oficina' => $this->input->post('cc_oficina'),
'dc' => $this->input->post('cc_dc'),
'cc' => $this->input->post('cc_cc'),
'centro' => $this->input->post('centro'),
'email' => $this->input->post('email'),
'especialidad' => $this->input->post('especialidad'),
'parent' => $this->session->userdata('parent')
);
// db adding
if( $this->users->add_user($user_data) )
{
// logged in!!
}
else
{
// grrr error!!
}
It looks much pretty now! :)
Hope this helps some lost souls to DO NOT construct the AR data array into the model, but the controller.

Resources