Laravel Changing Request data in Form Request Class - php

I'm processing a form with multiple date input which is not in A.D. For validation purpose i'm using Form Request.
Before validation and inserting in my database date input must be converted into A.D, so that i can do the proper validation & then if validation succeed date input is stored in A.D .
here is my code for converting date input in A.D
<?php
abstract class Request extends FormRequest
{
public function all()
{
$input = parent::all()
foreach ($input as $key=>$value)
{
if (substr($key, -5) == "_date")
{
$input[$key] = Helper::convert_in_ad($value);
}
}
return $input;
}
}
Now the problem is suppose you have failed validation and redirect back to the previous action and you then use old() or some other method to access the request data from the session, it will be modified, and i cannot get the the original data.
How can i change the date input in A.D when before validation so that i can properly validate in A.D and then store all the date input in A.D. by solving failed validation problem having modified input.
Edit Question
update:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\Contracts\CourseInterface;
use App\Repositories\Contracts\ClassInterface;
use App\Http\Requests\ClassRequest;
use App\Helpers\Helper;
class ClassController extends Controller
{
public function __construct(ClassInterface $class, CourseInterface $course)
{
$this->class = $class;
$this->course = $course;
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$classes = $this->class->paginate();
return view('backend.class.index')->with([
'classes' => $classes
]);
/*return view('backend.class.index')->with([
'classes' => $classes
]);*/
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$courses = $this->course->all();
return view('backend.class.create')->with([
'courses' => $courses
]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ClassRequest $request)
{
// dd($request->all());
$this->class->create($request->all());
return redirect()->route('classes.index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$class = $this->class->find($id);
$courses = $this->course->all();
return view('backend.class.edit')->with([
'class' => $class,
'courses' => $courses
]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(ClassRequest $request, $id)
{
$class = $this->class->update($request->all(), $id);
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->class->delete($id);
return redirect()->route('classes.index');
}
public function delete($id)
{
$class = $this->class->find($id);
return view('backend.class.delete')->with([
'class' => $class
]);
}
}
My class Request File
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Helpers\Helper;
class ClassRequest extends Request
{
public function all()
{
$input = parent::all();
foreach ($input as $key=>$value)
{
if (substr($key, -5) == "_date")
{
$input[$key] = Helper::convert_in_ad($value);
}
}
return $input;
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
//$this->sanitize();
switch($this->method())
{
case 'GET':
case 'DELETE':
{
return [];
}
case 'POST':
{
return [
'name' => 'required',
'course_id' => 'required',
'start_date' => 'required|date',
'end_date' => 'date|after:start_date',
];
}
case 'PUT':
case 'PATCH':
{
return [
'name' => 'required',
'course_id' => 'required',
'start_date' => 'required|date',
'end_date' => 'date|after:start_date',
];
}
default:break;
}
}
}
For validation purpose i need to change the date from B.S in A.D because laraval validation don't recognize B.S date. If i convert date in request file the problem is if validation fails i get the modified request back in form after redirect.
So how can i validate the date by converting it into A.D. The date in database table must be stored in A.D format for that i can use Accessors and Mutators the main problem is how to validate the data which user input in B.S format.
Edit After the suggestion i got
Thank you all for the suggestion, thank you very much for your help. One way i can validate is by making a custom validation rule as suggested. Right now i have another idea for making this work.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Helpers\Helper;
abstract class Request extends FormRequest
{
/**
* Sanitize input before validation
*
* #return array
*/
public function validator($factory)
{
return $factory->make(
$this->sanitizeInput(), $this->container->call([$this, 'rules']), $this->messages()
);
}
protected function sanitizeInput()
{
if (method_exists($this, 'sanitize'))
{
return $this->container->call([$this, 'sanitize']);
}
return $this->all();
}
/**
* Check for input having _date for converting it into AD
*
* #return array
*/
public function sanitize()
{
$input = $this->all();
foreach ($input as $key=>$value)
{
if (substr($key, -5) == "_date")
{
$input[$key] = Helper::convert_in_ad($value);
}
}
return $input;
}
}
By using the following code request data is not changed. And There will be no need for creating custom validation and this will be easy if i later decided to take date in A.D from user then changing every request file for updating validation rule wont be necessary.
What do you think about this?

As has been mentioned in the comments you should try and avoid editing the data in your FormRequest.
What you could do is define a new validation rule specifically for this: https://laravel.com/docs/5.3/validation#custom-validation-rules
So, in your app/Providers/AppServiceProvider (or another registered ServiceProvider) you could have something like:
Validator::extend('bs_date', function ($attribute, $value, $parameters, $validator) {
$date = date_parse(Helper::convert_in_ad($value));
return checkdate($date['month'], $date['day'], $date['year']);
}, 'Your error message');
Validator::extend('bs_after', function ($attribute, $value, $parameters, $validator) {
$data = $validator->getData();
$before = Helper::convert_in_ad($data[$parameters['0']]);
$after = Helper::convert_in_ad($value);
return (new \DateTime($before)) < (new \DateTime($after));
}, 'Your error message');
Rules
'start_date' => 'required|bs_date',
'end_date' => 'date|bs_after:start_date',
Obviously, don't forget to import Validator and Helper in the ServiceProvider.
This should mean that you don't have to edit your input anymore.
Hope this helps!

Related

Laravel validation rule for either of two fields required but both should not be present

Is there a Laravel validation rule for when either of two fields are required but both should not be present at the same time.
Eg. Mobile number and email, either of them should be present but not both.
Unfortunately, I couldn't find one.
To meet your needs, below are the steps I took.
Laravel has a validation rule for the case of making one request param required if the others aren't present.
required_without:foo,bar,...
The field under validation must be present and not empty only when any
of the other specified fields are not present.
For the case of achieving the, not both case, I had to come up with a custom validation rule.
STEPS
2a. Open your terminal and run the command to generate a custom validation rule.
php artisan make:rule OneOf
Here OneOf is my validation rule name. Name it anything you want. (use PascalCase).
2b. Open the generated file add your logic.
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Http\Request;
class OneOf implements Rule
{
public $oneOf = [];
public $request = null;
public $message = "";
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct(Request $request, array $oneOf, string $message = "")
{
$this->oneOf = $oneOf;
$this->request = $request;
$this->message = $message;
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$count = 0;
foreach ($this->oneOf as $param) {
if($this->request->has($param)){
$count++;
}
}
return count($this->oneOf) && ($count === 1) ? true : false;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
$json_encodedList = json_encode($this->oneOf);
return strlen(trim($this->message)) ? $this->message : "Please insert one of $json_encodedList.";
}
}
2c. In your controller, make use of the created custom rule.
<?php
namespace App\Http\Controllers\Employee;
use App\Http\Controllers\Controller;
use App\Rules\OneOf;
use Illuminate\Http\Request;
/**
* Class Employee
* #package App\Http\Controllers\Employee
*/
class Employee extends Controller
{
public function store(Request $request)
{
$request->validate([
"email" => ["required_without:phone_number", new OneOf($request, ["email", "phone_number"])],
"phone_number" => ["required_without:email", new OneOf($request, ["email", "phone_number"])],
]);
// ...Custom project specific logic here
return response()->json([]);
}
}
You can supply a custom message if you wish.
You can also apply it to more than two request params.
I've updated this code a little bit to ensure that things are not counted if they are null. A request can have a parameter, but that parameter be null, and the rule will still fire as invalid even though one of the two fields provided has nothing in it.
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class OneOf implements Rule
{
public $oneOf = [];
public $request = null;
public $message = "";
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct(Request $request, array $oneOf, string $message = "")
{
$this->oneOf = $oneOf;
$this->request = $request;
$this->message = $message;
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$count = 0;
foreach ($this->oneOf as $param) {
if($this->request->has($param) && $this->request->$param != null){
$count++;
}
}
return count($this->oneOf) && ($count === 1) ? true : false;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
$i = 1;
$length = count($this->oneOf);
$fieldNames = null;
foreach($this->oneOf as $fieldName) {
if($i < $length) {
$fieldNames .= Str::replace('_', ' ', Str::title($fieldName)) . ', ';
} else {
$fieldNames .= Str::replace('_', ' ', Str::title($fieldName));
}
$i++;
}
return strlen(trim($this->message)) ? $this->message : "Only one of these fields should be used: $fieldNames.";
}
}
You can also achieve this by combining required_without and prohibited_unless.
For example:
[
'email' => 'required_without:name|prohibited_unless:name,""'
'name' => 'required_without:email|prohibited_unless:email,""'
]
Note: prohibited_unless is fairly new, available since Laravel 8

Laravel 5.5 use custom validation rule in validation request file?

Is it possible to use my custom validation rule in a validation request file?
i want to use my custom rule called EmployeeMail
here is the code of the request file
class CoachRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [];
if ($this->isMethod('post') ) {
$rules = [
'name' => 'required|string',
'email' => 'required|email|employeemail', <<<--- this
'till' => 'required|date_format:H:i|after:from',
];
}
//TODO fix this
//TODO add custom messages for every field
return $rules;
}
}
it gives me an error when i try to use it like this
Method [validateEmployeemail] does not exist.
code of custom rule
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class EmployeeMail implements Rule
{
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
// If mail is that of an employee and not a student pass it
return preg_match("/#test.nl$/", $value) === 1;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'Email is geen werknemers mail';
}
}
can i only use this custom rule like this?
$items = $request->validate([
'name' => [new FiveCharacters],
]);
Rutvij Kothari answered the question in the comments.
It seems you are validating string with a regular expression, the same logic can be achieved by regex buit-in validation method. Check it out. laravel.com/docs/5.5/validation#rule-regex No need to create your own validation rule. – Rutvij Kothari
If you want to use your validation pass it into an array. like this. 'email' => ['required', 'email', new employeemail]

Laravel 5.5 conditional form request validation rule on update

I created a validation rule for the image form.
It works fine on store method but I do not want the image field to be required on update because I may only update the title for example.
class ImageRequest extends Request
{
/**
* Rules array
*/
protected $rules = [
'title' => 'required|string|between:3,60',
'alt' => 'sometimes|string|between:3,60',
'image' => 'required|image|max:4000|dimensions:min_width=200,min_height=200',
];
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return $this->rules;
}
}
For unique validation we can add custom query conditions:
'email' => Rule::unique('users')->ignore($user->id, 'user_id')
or
'email' => Rule::unique('users')->where(function ($query) {
return $query->where('account_id', 1);
})
Is it a clean way to achieve something similar for required?
Apply required only for new images.
you Can use switch statement inside rule
public function rules()
{
switch ($this->method()) {
case 'GET':
case 'DELETE': {
return [];
}
case 'POST': {
return [
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email|unique:users,email,'.$this->id,
'password'=>'',
'dob'=>'required',
'phone_one'=>'required',
'phone_two'=>'required',
//'user_role'=>'required',
// 'profile_image'=>'required'
];
}
case 'PUT':
case 'PATCH': {
return [
];
}
default:break;
}
Also you can use condtion like on update yuo have id so based on that you can check whether its update or insert since on insert you dont have id so
Create another class that extends the Request class, DI that into your update controller action
class UpdateImageRequest extends Request
{
/**
* Rules array
*/
protected $rules = [
'title' => 'required|string|between:3,60',
'alt' => 'sometimes|string|between:3,60'
];
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return $this->rules;
}
}
much better way is to use nullable in Laravel 5.5 validations
Ref Docs
The field under validation may be null. This is particularly useful
when validating primitive such as strings and integers that can
contain null values.
class ImageRequest extends Request
{
/**
* Rules array
*/
protected $rules = [
'title' => 'required|string|between:3,60',
'alt' => 'nullable|string|between:3,60',
'image' => 'nullable|image|max:4000|dimensions:min_width=200,min_height=200',
];
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return $this->rules;
}
}
However I have used recently with image and it worked like charm for me. Give it a try!
The simplest way in this case in the other way. By default have rules for update and if it's store add required like so:
class ImageRequest extends Request
{
/**
* Rules array
*/
protected $rules = [
'title' => 'required|string|between:3,60',
'alt' => 'sometimes|string|between:3,60',
'image' => 'image|max:4000|dimensions:min_width=200,min_height=200',
];
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = $this->rules;
if ($this->isMethod('POST')) {
$rules['image'] = 'required|' . $rules['image']
}
return $rules;
}
}
I found a solution.
I renamed image into file.
The route is homestead.app/images/1 on update and homestead.app/images on store so the $image property will be $this->image = 1 on update and $this->image = null on store.
class ImageRequest extends Request
{
/**
* Rules array
*/
protected $rules = [
'title'=> 'required|string|between:3,60',
'alt' => 'sometimes|string|between:3,60',
'file' => [
'image',
'max:4000',
'dimensions:min_width=200,min_height=200',
],
];
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$this->rules['file'][] = is_null($this->image) ? 'required' : 'sometimes';
return $this->rules;
}
}

Class App\Http|Controllers\ValidateRegistraion does not exist

I have created a form request using php artisan make:request ValidateRegistration. It created a ValidateRegistration.php file under App\Http\Requests\ directory. After this I have made changes in the store() function of my registration controller ie UserController.php, means I have changed it
FROM
public function store(Request $request)
{
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
TO
public function store(ValidateRagistration $request)
{
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
And added use App\Http\Requests\ValidateRagistration; at the top of the UserController.php file. But when I submit the form without filling anything it shows me an error which is Class App\Http\Controllers\ValidateRegistraion does not exist
EDIT
Added UserController.php and ValidateRegistration.php files.
UserController.php
<?php
use App\Http\Requests\ValidateRegistration;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$title = "Registration";
return view('/registration', compact('title'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ValidateRegistration $request)
{
//// validate requested data
//$this->validate(request(), [
// 'fname' => 'required',
// 'lname' => 'required',
// 'phone' => 'required|size:10',
// 'email' => 'required',
// 'password' => 'required'
//]);
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
ValidateRegistration.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ValidateRegistration extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'fname' => 'required',
'lname' => 'required',
'phone' => 'required|size:10',
'email' => 'required',
'password' => 'required'
];
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [
'fname.required' => 'Firstname is mandatoy',
'lname.required' => 'Lastname is mandatory',
'phone.required' => 'Phone is mandatory',
'phone.size' => 'Phone must be 10 digit',
'email.required' => 'Email is mandatory',
'password.required' => 'Password is mandatory',
];
}
}
spot the difference in your class names:
ValidateRagistration
ValidateRegistraion
and I'm guessing it should read ValidateRegistration, clear up typos, they will only confuse things later
at the top of UserController.php swap the positions of the namespace and use lines, namespace should always be first
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ValidateRegistration;
use Illuminate\Http\Request;
use App\User;
and ValidateRegistration.php is in your App\Http\Requests directory
in ValidateRegistration.php I modified the authorize() function. It was returning false. Changed it to true. It is working now.
From
public function authorize()
{
return false;
}
To
public function authorize()
{
return true;
}

Laravel form validation unique using 2 fields

How can I have a unique validation rule on 2 fields?
a. The application should not allow two people to have the same identical first name and last name.
It is allowed that the users fills in only a first name or only a last name. Because the user may have only one of them.
b. But if the user enters only a first name (Glen), no other person in the table should have the same (first name = 'Glen' and last name = null). another 'Glen Smith' ok.
I tried the following rule. It works great when both fields (first and last name) are not null:
'firstName' => 'unique:people,firstName,NULL,id,lastName,' . $request->lastName
This rule fails on b. when only one field is present.
Any hint?
The built in unique validator wouldn't really support what you're trying to do. It's purpose is to ensure that a single valid is unique in the database, rather than a composite of two values. However, you can create a custom validator:
Validator::extend('uniqueFirstAndLastName', function ($attribute, $value, $parameters, $validator) {
$count = DB::table('people')->where('firstName', $value)
->where('lastName', $parameters[0])
->count();
return $count === 0;
});
You could then access this new rule with:
'firstName' => "uniqueFirstAndLastName:{$request->lastName}"
You'll probably find you might need to tweak your database query a little bit as it's untested.
I think you are looking for something like that:
'unique:table_name,column1,null,null,column2,'.$request->column2.',column3,check3'
This is an extensive answer to this question and how to create Laravel custom validator generally, you can simply copy and paste, and try to understand later:
Step 1: Create a provider app/Providers/CustomValidatorProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator as ValidatorFacade;
/**
* Provider for custom validators. Handles registration for custom validators.
*
*/
class CustomValidatorProvider extends ServiceProvider {
/**
* An array of fully qualified class names of the custom validators to be
* registered.
*
* #var array
*/
protected $validators = [
\App\Validators\MultipleUniqueValidator::class,
];
/**
* Bootstrap the application services.
*
* #return void
* #throws \Exception
*/
public function boot() {
//register custom validators
foreach ($this->validators as $class) {
$customValidator = new $class();
ValidatorFacade::extend($customValidator->getName(), function() use ($customValidator) {
//set custom error messages on the validator
func_get_args()[3]->setCustomMessages($customValidator->getCustomErrorMessages());
return call_user_func_array([$customValidator, "validate"], func_get_args());
});
ValidatorFacade::replacer($customValidator->getName(), function() use ($customValidator) {
return call_user_func_array([$customValidator, "replacer"], func_get_args());
});
}
}
/**
* Register the application services.
*
* #return void
*/
public function register() {
//
}
}
Step 2: Update your app.php in your config folder config/app.php to include your created provider in the provider array
App\Providers\CustomValidatorProvider::class,
Step 3: Create your custom validator, in my case, I am creating multiple unique fields validator app/Validators/MultipleUniqueValidator.php
<?php
namespace App\Validators;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Validation\Validator;
/**
* Multiple field uniqueness in laravel
*/
class MultipleUniqueValidator{
/**
* Name of the validator.
*
* #var string
*/
protected $name = "multiple_unique";
/**
* Return the name of the validator. This is the name that is used to specify
* that this validator be used.
*
* #return string name of the validator
*/
public function getName(): string {
return $this->name;
}
/**
*
* #param string $message
* #param string $attribute
* #param string $rule
* #param array $parameters
* #return string
*/
public function replacer(string $message, string $attribute, string $rule, array $parameters): string {
unset($parameters[0]);
$replacement = implode(", ", $parameters);
$replacement = str_replace("_", " ", $replacement);
$replacement = Str::replaceLast(", ", " & ", $replacement);
$replacement = Str::title($replacement);
return str_replace(":fields", "$replacement", $message);
}
/**
*
* #param string $attribute
* #param mixed $value
* #param array $parameters
* #param Validator $validator
* #return bool
* #throws \Exception
*/
public function validate(string $attribute, $value, array $parameters, Validator $validator): bool {
$model = new $parameters[0];
if (!$model instanceof Model) {
throw new \Exception($parameters[0] . " is not an Eloquent model");
}
unset($parameters[0]);
$this->fields = $parameters;
$query = $model->query();
$request = app("request");
foreach($parameters as $parameter){
$query->where($parameter, $request->get($parameter));
}
return $query->count() == 0;
}
/**
* Custom error messages
*
* #return array
*/
public function getCustomErrorMessages(): array {
return [
$this->getName() => ":fields fields should be unique"
];
}
}
Now you can do this in your request
'ANY_FIELD_CAN_CARRY_IT' => 'required|numeric|multiple_unique:'.YOUR_MODEL_HERE::class.',FIELD_1,FIELD_2,FIELD_3...',
Laravel now allows you to add where clauses into the unique rule.
In your case you could do something like this:
'firstName' => [
Rule::unique('people', 'firstName')->where(function ($query) use ($lastName) {
return $query->where('lastName', $lastName);
})
],
in my case this works just fine (in controller):
$request->validate([
'firstName' => 'required|min:3|max:255|unique:people,firstName,NULL,id,lastname,' . $request->input('lastname'),
], [
'unique' => 'Some message for "unique" error',
]);
You can do it if the Validator class isn't required for you:
if(Model::query()->where([
'column_1' => 'data_1',
'column_2' => 'data_2'
])->exists())
{
// some code..
}

Categories