Wednesday 20 September 2023

Laravel Rule Validations

Laravel validations

$errorMessage = "NFL Competition already exist for year $this->year and with the selected competition type.";

return [

    'name' => 'string',
    'abbreviation' => 'required|max:10',
    'year' => 'required|digits:4|integer|min:1900|max:' . (date('Y') + 1),
    'competition_type_id' => ['required', 'string', new IsCompositeUnique('basketball_competitions', ['year' => $this->year, 'competition_type_id' => $this->competition_type_id], $this->competition_id, $errorMessage)],

];





<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;

class IsCompositeUnique implements Rule
{
/**
* @var string
*/
private $tableName;
/**
* @var array
*/
private $compositeColsKeyValue = [];
/**
* @var mixed|null
*/
private $rowId;

private $errorMessage;

/**
* Create a new rule instance.
*
* @return void
*/
public function __construct(string $tableName, array $compositeColsKeyValue, $rowId = null, $errorMessage = null)
{
$this->tableName = $tableName;
$this->compositeColsKeyValue = $compositeColsKeyValue;
$this->rowId = $rowId;
$this->errorMessage = $errorMessage;
}

/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value): bool
{
if ($this->rowId) {
$record = DB::table($this->tableName)->where($this->compositeColsKeyValue)->first();
$passess = !$record || ($record && $record->id == $this->rowId);
} else {
$passess = !DB::table($this->tableName)->where($this->compositeColsKeyValue)->exists();
}

return $passess;
}

/**
* Get the validation error message.
*
* @return string
*/
public function message(): string
{
if ($this->errorMessage) {
return $this->errorMessage;
}
$colNames = '';
foreach ($this->compositeColsKeyValue as $col => $value) {
$colNames .= $col . ', ';
}
$colNames = rtrim($colNames, ', ');

return "The combination of $colNames must be unique.";
}
}
Share:

0 comments:

Post a Comment

Popular Posts

Recent Posts

Pages

Powered by Blogger.

About Me

My photo
For the past 10 years, I've been playing with codes using PHP, Java, Rails. I do this for a living and love new things to learn and the challenges that comes with it. Besides programming I love spending time with friends and family and can often be found together catching the latest movie or planning a trip to someplace I've never been before.