I
I
igor11122019-03-26 18:40:15
Laravel
igor1112, 2019-03-26 18:40:15

Unique fields and validation?

I have a table with a unique combination of fields, in the migration I specified like this -

$table->string('поле1');
$table->integer('поле2');
$table->unique(['поле1', 'поле2']);

That is, a bunch of fields "field1" and "field2" must be unique in this table.
Question - how do I validate in the column controller "field1" when saving and updating?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Aksentiev, 2019-03-26
@Sanasol

You take and check the existence of such a combination in the database, it is not clear what exactly the complexity is.

if(Model::where('field1', $field1)->where('field2', $field2)->exists()) { 
//нельзя так делать 
}

A
Alexander, 2019-03-26
@xpert13

$messages = [
    'data.ip.unique' = 'Given ip and hostname are not unique',
];

Validator::make($data, [
    'data.ip' => [
        'required',
        Rule::unique('servers')->where(function ($query) use($ip,$hostname) {
            return $query->where('ip', $ip)
            ->where('hostname', $hostname);
        }),
    ],
],
$messages
);

(c) https://stackoverflow.com/questions/50349775/larav...
But as for me - such a solution. It's better to actually write your own rule.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question