Laravel unique field validate not working - validation

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})$/',
];

Related

cannot add or update a child row a foreign key constraint fails laravel factory

I have users table with 20 rows.
When I factored user_transaction table, I see this error.
Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fa
ils (webafra_testa.user_transaction, CONSTRAINT user_transaction_userid_foreign FOREIGN KEY (userId) REFERENCES users (id) ON DELETE CASCADE) (SQL: inse
rt into user_transaction (userId, price, description, type, traceableId, receptorId, status, paymentMethod, tracking_code, created_at, update d_at) values (0, 5, Voluptatem assumenda facilis perferendis nihil est., money_transfer, 1, 1, waiting_payment, online, 1, 2021-05-29 10:41:30, 2021-05-29 10:41:30
))'
factory
$factory->define(UserTransaction::class, function (Faker $faker) {
return [
'userId' => $faker->randomKey([1, 20]),
'price' => $faker->randomDigit,
'description' => $faker->sentence(5),
'type' => $faker->randomElement(['order', 'sub_factor', 'money_transfer', 'increase_inventory', 'application_fee']),
'traceableId' => $faker->randomKey([1000, 9999]),
'receptorId' => $faker->randomKey([1000, 9999]),
'status' => $faker->randomElement(['done', 'canceled', 'waiting_payment']),
'paymentMethod' => $faker->randomElement(['tesseke', 'cash', 'online']),
'tracking_code' => $faker->randomKey([1000, 9999]),
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
];
});
'userId' => $faker->numberBetween(1, 20)
also for the others where you used randomKey , change it to numberbetween

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?

Use sort order from TCA select to list items in fluid

In my TCA I use a select to an other table.
'modules' => [
'label' => 'LLL:EXT:myextension_module_table/Resources/Private/Language/locallang_db.xlf:tx_myextension_domain_model_semester.modules',
'config' => [
'type' => 'select',
'renderType' => 'selectMultipleSideBySide',
'enableMultiSelectFilterTextfield' => true,
'foreign_table' => 'tx_myextension_domain_model_module',
'minitems' => 1,
'maxitems' => 99,
],
],
Under "Selected Items" I can sort the items. Now I want to use this sort order in fluid. In database I see the right order 21,1,2,3,4,28. But in fluid the items are always sorted by uid.
Adding 'sortby' => 'sorting', with all needed changes doesn't solve my problem. In this case I can order records in list view. But I don't want this order. I want to show order from "Selected Items" in frontend.
In my ModuletableController.php I get the selected moduletable from Flexform.
/**
* action show
*
* #param \Vendor\Myextension\Domain\Model\Moduletable $moduletable
* #return void
*/
public function showAction(\Vendor\Myextension\Domain\Model\Moduletable $moduletable = NULL) {
if (is_null($moduletable)) {
$moduletable = $this->moduletableRepository->findByUid($this->settings['singleModuleTable']);
}
$this->view->assign('moduletable', $moduletable);
}
An in the template Show.html I loop through it.
<html xmlns:f="http://typo3.org/ns/TYPO3/Fluid/ViewHelpers">
<f:layout name="Default" />
<f:section name="main">
<h2>{moduletable.title}</h2>
<f:for each="{moduletable.semester}" as="semester">
<p>{semester.title}</p>
<f:for each="{semester.modules}" as="module">
<p{module.title}</p>
</f:for>
</f:for>
</f:section>
Solution is to use MM tables. Then sort order is set in TCA select field.
In TCA:
'modules' => [
'label' => 'LLL:EXT:myextension/Resources/Private/Language/locallang_db.xlf:tx_myextension_domain_model_semester.modules',
'config' => [
'type' => 'select',
'renderType' => 'selectMultipleSideBySide',
'enableMultiSelectFilterTextfield' => true,
'foreign_table' => 'tx_myextension_domain_model_module',
'foreign_sortby' => 'sorting',
'MM' => 'tx_myextension_semester_module_mm',
'minitems' => 1,
'maxitems' => 99,
],
],
In ext_tables.sql
CREATE TABLE tx_myextension_semester_module_mm (
uid_local int(11) unsigned DEFAULT '0' NOT NULL,
uid_foreign int(11) unsigned DEFAULT '0' NOT NULL,
sorting int(11) unsigned DEFAULT '0' NOT NULL,
sorting_foreign int(11) unsigned DEFAULT '0' NOT NULL,
KEY uid_local (uid_local),
KEY uid_foreign (uid_foreign)
);
How do you get the selected items in your Extbase controller? Maybe you can use this findByUidListOrderByList function here: http://blog.teamgeist-medien.de/2014/09/typo3-extbase-repository-find-by-multiple-uids-findbyuids.html#comment-90

laravel 5 issue with slashes in query

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

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