I'm working on a Laravel 9 project and have created a custom validation rule called ValidModelOwnership which should check that the field a user is trying to add is owned by a model based on some values passed to it.
I've written the rule, but when debugging and outputting $model->toSql() the id is empty?
What am I missing?
My rule:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Log;
class ValidModelOwnership implements Rule
{
/**
* The model we're checking
*/
protected $model;
/**
* Array of ownership keys
*/
protected $ownershipKeys;
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct($model, $ownershipKeys)
{
$this->model = $model;
$this->ownershipKeys = $ownershipKeys;
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$model = $this->model::query();
$model = $model->where($this->ownershipKeys);
Log::debug($model->toSql());
if (!$model->exists()) {
return false;
}
return true;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return "The :attribute field doesn't belong to you and/or your company.";
}
}
And my usage in my controller:
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store($company_id, $buyer_id, Request $request)
{
$this->authorize('create', BuyerTier::class);
$validator = Validator::make($request->all(), [
'name' => [
'required',
'string',
Rule::unique(BuyerTier::class)
->where('buyer_id', $buyer_id)
->where('company_id', $company_id)
],
'country_id' => [
'required',
'numeric',
new ValidModelOwnership(Country::class, [
['company_id', 80]
])
],
'product_id' => [
'required',
'numeric',
new ValidModelOwnership(Product::class, [
['company_id', 80]
])
],
'processing_class' => 'required|string',
'is_default' => [
'required',
'boolean',
new ValidDefaultModel(BuyerTier::class, $buyer_id)
],
'is_enabled' => 'required|boolean'
]);
if ($validator->fails()) {
return response()->json([
'message' => 'One or more fields has been missed or is invalid.',
'errors' => $validator->messages(),
], 400);
}
try {
$tier = new BuyerTier;
$tier->user_id = Auth::id();
$tier->company_id = $company_id;
$tier->buyer_id = $buyer_id;
$tier->country_id = $request->input('country_id');
$tier->product_id = $request->input('product_id');
$tier->name = trim($request->input('name'));
$tier->description = $request->input('description') ?? null;
$tier->processing_class = $request->input('processing_class');
$tier->is_default = $request->boolean('is_default');
$tier->is_enabled = $request->boolean('is_enabled');
$tier->save();
return response()->json([
'message' => 'Buyer tier has been created successfully',
'tier' => $tier
], 201);
} catch (\Exception $e) {
return response()->json([
'message' => $e->getMessage()
], 400);
}
}
I've hard-coded my id's to illustrate that even when set statically, it's not passed through:
[2023-01-19 09:40:59] local.DEBUG: select * from products where (company_id = ?) and products.deleted_at is null
Laravel (and most other frameworks) extract out variables when building SQL queries to prevent SQL injection.
So the following eloquent query:
User::where('name', 'Larry');
will become:
SELECT * FROM `users` WHERE `name` = ?
and it will also pass an array of bindings: ['Larry']. When SQL processes the query it replaces replaces the ? with the values in the bindings.
So if you want to see the full query you need to log the SQL and the bindings:
Log::debug($model->toSql());
Log::debug($model->getBindings());
I'm trying to update a company data using CompanyRequest but got an error. Please see my code below and other details.
CompanyRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;
class CompanyRequest 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()
{
if($this->isMethod('PATCH')) {
return [
'name' => [
'required',
'max:255',
Rule::unique('companies')->ignore($this->id)
],
'owner' => 'required|max:255',
'address' => ''
];
}
return [
'name' => 'required|max:255|unique:companies',
'owner' => 'required|max:255',
'address' => ''
];
}
}
CompanyController.php
public function update(Company $company, CompanyRequest $request)
{
return $company->update($request->validated());
}
api.php
Route::patch('company/{company}', [CompanyController::class, 'update'])->name('company.update');
Error
I think you need to use the same property as the route
Rule::unique('companies')->ignore($this->company)
Try something like
'name' => 'unique:companies,name,' . $id,
so basically name is unique, but allow update when id is same.
To tell the unique rule to ignore the user's ID, you may pass the ID as the third parameter:
'name' => 'unique:companies,column,'.$this->id
I'm using Laravel and I have a custom validation. I want to pass some value to the validation class and validate it against the DB so I keep all the validation logic in the validation class. Here's my code but the validation error is not triggered:
public function rules() {
$userCode = UserCode::getCode();
$rules = [
'name' => 'required|string',
'email' => 'required|email',
$userCode => 'unique:user_codes,code,'. $userCode
];
return $rules;
}
What am I doing wrong here? the validation is never triggered even if the value $userCode already exists in the DB. The validation is triggered if the request contains bad email for example.
Edit: I have this user_codes table that has a code column that must be kept unique. UserCode::getCode() produces this code. So I also want to check if this code is unique or not in the table user_codes before passing it to the controller. I already have the custom validator but the problem is that I want it to also validate this code. The validator works fine with the other request body. The problem is that this code is not passed from the request body but it is simply generated from another method.
You could do this using a FormRequest class with the prepareForValidation() method. It should look something like this:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class WhateverRequest extends FormRequest
{
protected function prepareForValidation(): void
{
$this->merge([
'user_code' => UserCode::getCode(),
]);
}
public function rules(): array
{
return [
'name' => 'required|string',
'email' => 'required|email',
'user_code' => 'unique:user_codes,code'
];
}
}
your question is not clear, I understand you have a column named by code
and you want to be unique, you can add usercode to request,
request()->merge(['userCode'=>$userCode]);
then
$rules = [
'name' => 'required|string',
'email' => 'required|email',
'userCode' => 'unique:user_codes,code,'.UserCode::getId().',id'
];
I answered what I understand from your question
Okay start with the following:
php artisan make:rule SomeAwesomeRule
Then edit that created Rule
class SomeAwesomeRule 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)
{
//some logic that needs to be handled...
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return __('Some.nice.translated.message');
}
}
And then apply the rule
$rules = [
'name' => 'required|string',
'email' => 'required|email',
'userCode' => new SomeAwesomeRule(#this is a constructor so pass away)
];
see
$rules = [
'name' => 'required|string',
'email' => 'required|email',
'userCode' => 'unique:user_codes,code'
];
//or
$userCode="";
do{
$userCode = UserCode::getCode();
}
while(UserCode::where('code',$userCode)->first());
// after loop you sure the code is unique
$rules = [
'name' => 'required|string',
'email' => 'required|email',
];
I'm using FormRequest for Validation.
I'm creating record in DB. There a some fields which are not required, how can i get them through FormRequest. At, the moment i'm only getting fields which are in rules() method.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CategoryRequest 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()
{
return [
'title_tr' => 'required|min:2|max:255',
'description_tr' => 'required',
'parent_id' => 'required',
'seo_title_tr' => 'required',
'meta_description_tr' => 'required'
];
}
public function messages(){
return [
'title_tr.required' => trans('admin.category.validation_errors.title_tr'),
'description_tr.required' => trans('admin.category.validation_errors.description_tr'),
'seo_title_tr.required' => trans('admin.category.validation_errors.seo_title_tr'),
'meta_description_tr.required' => trans('admin.category.validation_errors.meta_description_tr'),
];
}
}
you can use sometimes
Validating When Present In some situations, you may wish to run
validation checks against a field only if that field is present in the
input array. To quickly accomplish this, add the sometimes rule to
your rule list:
public function rules()
{
return [
'username' => 'sometimes',
];
}
You can make it nullable as shown below.
public function rules()
{
return [
// ...
'not_required_field' => 'nullable',
];
}
I'm trying to create customized messages for validation in Laravel 5. Here is what I have tried so far:
$messages = [
'required' => 'Harap bagian :attribute di isi.',
'unique' => ':attribute sudah digunakan',
];
$validator = Validator::make($request->all(), [
'username' => array('required','unique:Userlogin,username'),
'password' => 'required',
'email' => array('required','unique:Userlogin,email'),$messages
]);
if ($validator->fails()) {
return redirect('/')
->withErrors($validator) // send back all errors to the login form
->withInput();
} else {
return redirect('/')
->with('status', 'Kami sudah mengirimkan email, silahkan di konfirmasi');
}
But it's not working. The message is still the same as the default one. How can I fix this, so that I can use my custom messages?
Laravel 5.7.*
Also You can try something like this. For me is the easiest way to make custom messages in methods when you want to validate requests:
public function store()
{
request()->validate([
'file' => 'required',
'type' => 'required'
],
[
'file.required' => 'You have to choose the file!',
'type.required' => 'You have to choose type of the file!'
]);
}
If you use $this->validate() simplest one, then you should write code something like this..
$rules = [
'name' => 'required',
'email' => 'required|email',
'message' => 'required|max:250',
];
$customMessages = [
'required' => 'The :attribute field is required.'
];
$this->validate($request, $rules, $customMessages);
You can provide custom message like :
$rules = array(
'URL' => 'required|url'
);
$messages = array(
'URL.required' => 'URL is required.'
);
$validator = Validator::make( $request->all(), $rules, $messages );
if ( $validator->fails() )
{
return [
'success' => 0,
'message' => $validator->errors()->first()
];
}
or
The way you have tried, you missed Validator::replacer(), to replace the :variable
Validator::replacer('custom_validation_rule', function($message, $attribute, $rule, $parameters){
return str_replace(':foo', $parameters[0], $message);
});
You can read more from here and replacer from here
For Laravel 8.x, 7.x, 6.x
With the custom rule defined, you might use it in your controller validation like so :
$validatedData = $request->validate([
'f_name' => 'required|min:8',
'l_name' => 'required',
],
[
'f_name.required'=> 'Your First Name is Required', // custom message
'f_name.min'=> 'First Name Should be Minimum of 8 Character', // custom message
'l_name.required'=> 'Your Last Name is Required' // custom message
]
);
For localization you can use :
['f_name.required'=> trans('user.your first name is required'],
Hope this helps...
$rules = [
'username' => 'required,unique:Userlogin,username',
'password' => 'required',
'email' => 'required,unique:Userlogin,email'
];
$messages = [
'required' => 'The :attribute field is required.',
'unique' => ':attribute is already used'
];
$request->validate($rules,$messages);
//only if validation success code below will be executed
//Here is the shortest way of doing it.
$request->validate([
'username' => 'required|unique:Userlogin,username',
'password' => 'required',
'email' => 'required|unique:Userlogin,email'
],
[
'required' => 'The :attribute field is required.',
'unique' => ':attribute is already used'
]);
//The code below will be executed only if validation is correct.
run below command to create a custom rule on Laravel
ı assuming that name is CustomRule
php artisan make:rule CustomRule
and as a result, the command was created such as PHP code
if required keyword hasn't on Rules,That rule will not work
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class CustomRule 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)
{
//return true or false
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The validation error message.';
}
}
and came time using that
first, we should create a request class if we have not
php artisan make:request CustomRequest
CustomRequest.php
<?php
namespace App\Http\Requests\Payment;
use App\Rules\CustomRule;
use Illuminate\Foundation\Http\FormRequest;
class CustomRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules(): array
{
return [
'custom' => ['required', new CustomRule()],
];
}
/**
* #return array|string[]
*/
public function messages(): array
{
return [
'custom.required' => ':attribute can not be empty.',
];
}
}
and on your controller, you should inject custom requests to the controller
your controller method
class FooController
{
public function bar(CustomRequest $request)
{
}
}
You can also use the methods setAttributeNames() and setCustomMessages(),
like this:
$validation = Validator::make($this->input, static::$rules);
$attributeNames = array(
'email' => 'E-mail',
'password' => 'Password'
);
$messages = [
'email.exists' => 'No user was found with this e-mail address'
];
$validation->setAttributeNames($attributeNames);
$validation->setCustomMessages($messages);
For those who didn't get this issue resolve (tested on Laravel 8.x):
$validated = Validator::make($request->all(),[
'code' => 'required|numeric'
],
[
'code.required'=> 'Code is Required', // custom message
'code.numeric'=> 'Code must be Number', // custom message
]
);
//Check the validation
if ($validated->fails())
{
return $validated->errors();
}
$rules = [
'name' => 'required',
'email' => 'required|email',
'message' => 'required|max:250',
];
$customMessages = [
'required' => 'The :attribute field is required.',
'max' => 'The :attribute field is may not be greater than :max.'
];
$this->validate($request, $rules, $customMessages);
In the case you are using Request as a separate file:
public function rules()
{
return [
'preparation_method' => 'required|string',
];
}
public function messages()
{
return [
'preparation_method.required' => 'Description is required',
];
}
Tested out in Laravel 6+
you can customise the message for different scenarios based on the request.
Just return a different message with a conditional.
<?php
namespace App\Rules;
use App\Helpers\QueryBuilderHelper;
use App\Models\Product;
use Illuminate\Contracts\Validation\Rule;
class ProductIsUnique implements Rule
{
private array $attributes;
private bool $hasAttributes;
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct(array $attributes)
{
$this->attributes = $attributes;
$this->hasAttributes = true;
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$brandAttributeOptions = collect($this->attributes['relationships']['brand-attribute-options']['data'])->pluck('id');
$query = Product::query();
$query->when($brandAttributeOptions->isEmpty(), function ($query) use ($value) {
$query->where('name', $value);
$this->hasAttributes = false;
});
return !$query->exists();
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return ($this->hasAttributes) ? 'The Selected attributes & Product Name are not unique' : 'Product Name is not unique';
}
}
Laravel 10.x
If you are using Form Requests, add another method called messages(): array in your request.
class YourRequest extends FormRequest
{
public function rules(): array
{
return [
'name' => 'required',
'email' => 'required|email',
...
];
}
//Add the following method
public function messages(): array
{
return [
'email.required' => 'Custom message for Email Required',
];
}
}
Then the message will be displayed automatically once the request is send from the form.