i new in laravel i trying to make custom validation rule to validate name of brand i make this rule and worked normally :-
public function update(Request $request, $id)
{
//prepare data for validation
request()->validate([
'name' => [
'required',
'min:2', // validate english name is exist before
**function ($attribute, $value, $fail) {
$englishname=Brand::where(['name'=>$value,'deleted'=>1 ])->first();
if(false !=$englishname) {
$fail('Opps '.$attribute.' Is Exist Before.');
}**
},
],
],[],[
"name"=>"Brand Name",
]);
validate name success and no problem but my real problem is how link id of brand in case of edit data to make this function
**$englishname=Brand::where(['name'=>$value,'deleted'=>1,'id'=>$id ])->first()**
how to right function in validator ?
$this->validate($request,[
'name'=>['required',Rule::unique('brands')->where('deleted_at',1)],
]);
Note : please import Rule at top.
How to update existing current name ?
Code Below :
public function update(Request $request, $id)
{
$this->validate($request,[
'name'=>['required',Rule::unique('brands')->ignore($id)],
]);
}
If I understand correctly, you try to make brand name unique, so you can try this:
request()->validate([
'name' => 'required|unique:<table name>,name'
]);
You can write custom validate and notification
public function update(Request $request, $id)
{
$this->validate($request,[
'name'=>['required',Rule::unique('brands')->ignore($id)],
],
[
'required'=>'This field is required',
]);
}
Related
I have already asked question about Laravel 5.7 validation, however it still does not work quite right. the validation is not executed at all when sending the content.
public function store(Request $request)
{
$data=$request->all();
$validator = Validator::make($data, [
'first_name' => 'alpha|min:2|max:30',
]);
}
Thanks in advance
if your are not using form validation then maybe it will be helpful for you.
I add validator example in your code, you can try it
maybe your problem will resolve
public function update(Request $request, Player $player)
{
//example validation
$validator = Validator::make($request->all(), [
'id' => 'required|integer', //put your fields
'text' => 'required|string' //put your fields
]);
if ($validator->fails()){
return "Invalid Data";
}
if(Auth::check()){
$playerUpdate = Player::where('id', $player->id)
->update([
'first_name' => $request->input('fist_name'),
'last_name' => $request->input('last_name')
]);
if($playerUpdate){
return redirect()->route('players.show', ['player'=> $player->id])
->with('success' , 'player foo');
}
}
return back()->withInput()->with('errors', 'Foo error');
}
I don't see your validation code at all.
there are two ways for implementing the validation in laravel
Form Request Validation
validation in controller methods
Please Add one, and try again
I create laravel form validation request and have unique rules on that validation.
I want use it on store and update method without create new form request validation again.
but the problem is when on store the id doesnt exist and the validate is passed
and when on update i failed the pass the validating because the id is exist on storage
i want to ignore the id on unique rules but use same form validate request
what is best practice to check on form validate request class if this action from store or update method to ignore unique id ?
Ok.. i can do it like #porloscerros Ψ suggest
public function rules()
{
$rules = [
'name' => 'required|string|unique:products|max:255',
];
if (in_array($this->method(), ['PUT', 'PATCH'])) {
$product = $this->route()->parameter('product');
$rules['name'] = [
'required',
'string',
'max:255',
Rule::unique('loan_products')->ignore($product),
];
}
return $rules;
}
Try this, it worked for me.
Laravel unique: third param can exclude the id for example, of the record, like this:
public function rules()
{
return [
'name' => 'required|string|max:255|unique:products,'.$this->id,
];
}
Why are you checking the id when store or update in FormRequest? You don't need this. The id comes to your controller's method like as parameter. Or laravel will create the model using DI in the your controller's method public function update(User $user) and then you can use $user like an instance of User model. You may check the id in web.php or api.php:
https://laravel.com/docs/7.x/routing#parameters-regular-expression-constraints
And I suggest you not to use one FormRequest for two methods. This is bad practice
im using this
$validated = $request->validated();
use this method:
public function createAccount(RegisterRequest $request)
{
$attr = $request->validated();
instead of something like this:
public function createAccount(Request $request)
{
$attr = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string|min:6|confirmed'
]);
use php artisan make:request RegisterRequest
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string|min:6|confirmed'
];
}
public function rules()
{
if (request()->isMethod('post')) {
$rules = [
'image' => 'required|image|mimes:jpeg,jpg,png|max:2000',
'name' => 'required|unique:categories'
];
} elseif (request()->isMethod('PUT')) {
$rules = [
'name' => 'required|unique:categories,name'
];
}
return $rules;
}
In my UpdateUserRequest class I have a validation rule that requires using the page ID to exclude the current record from validation. Question is, how can I get the current page ID?
public function rules()
{
return [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users_admin,email,'. $page_id,
];
}
I know how to do it without the FormRequest class basically by just using the update(Request $request, $id) method in the controller.
I have tried doing this basic way which is by writing a update(Request $request, $id) method in the controller and performing the validations in there. The validation works as expected but then there's another problem of the page wasn't redirecting properly in the Backpack admin after saving.
I actually prefer this basic approach (using store() and update() methods in the controller) than having to have separate FormRequest classes for create and update validations.
Thank you.
We can get the id with the below simple way , i have tried it and it works for me.
public function rules()
{
$page_id = $this->get('id') ?? request()->route('id');
return [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users_admin,email,'. $page_id,
];
}
Referenced from the below mentioned url
https://github.com/Laravel-Backpack/PermissionManager/blob/master/src/app/Http/Requests/UserUpdateCrudRequest.php
It's better to use the unique method of the Illuminate\Validation\Rule class:
public function rules(): array
{
return [
'name' => [
'required',
Rule::unique('post')->ignore(request()->route('id'))
],
];
}
Detailed description in laravel documentation:
https://laravel.com/docs/9.x/validation#rule-unique
I'm going straight to the point here, I am wondering if it is possible to pass a parameter on a validation rule in Laravel.
Here's my code:
I need to pass the $product->id to the ProductUpdateRequest class.
I've read some articles and to no avail can't pass a parameter into it. my other solution was to not use the validation rule class and do the validation directly on the controller by using $request->validate[()]. Since I can access the $product->id on the controller I can easily do the validation. but out of curiosity is there a way for me to pass the $product->id on the validation class?
CONTROLLER
public function update(ProductUpdateRequest $request, Product $product)
{
$request['detail'] = $request->description;
unset($request['description']);
$product->update($request->all());
return response([
'data' => new ProductResource($product)
], Response::HTTP_CREATED);
}
VALIDATION RULE
public function rules()
{
return [
'name' => 'required|max:255|unique:products,name'.$product->id,
'description' => 'required',
'price' => 'required|numeric|max:500',
'stock' => 'required|max:6',
'discount' => 'required:max:2'
];
}
Any suggestions/answers/help would be highly appreciated.
You can get the resolved binding from request
$product = $this->route('product');
Inside your rules method you can get the product instance with the above method.
public function rules()
{
$product = $this->route('product');
return [
'name' => 'required|max:255|unique:products,name'.$product->id,
'description' => 'required',
'price' => 'required|numeric|max:500',
'stock' => 'required|max:6',
'discount' => 'required:max:2'
];
}
It works when you make a function with this Product $product (when you used the Resource route in most cases)
public function update(ProductUpdateRequest $request, Product $product)
{
// code goes here
}
but if you make it like the below it won't work ()
public function update(ProductUpdateRequest $request, $id)
{
// code goes here
}
This is how I would validate unique product name on update. I pass the product ID as a route parameter, the use the unique validation rule to validate that it the product name does't exist in the Database except for this product (id).
class ProductController extends Controller {
public function update(Request $request, $id) {
$this->validate($request, [
'name' => 'required|max:255|unique:products,name'.$id,
]);
// ...
}
}
For custom request in validation rule you can put in your
View :
<input type="hidden" value="product_id">
In Validation Request :
public function rules()
{
$product_id = $this->request->get('product_id');
return [
//
];
}
I use PUT routing:
Route::put('offers/{id}/accept', 'OfferController#accept');
And controller:
public function accept(Request $request, $id)
{
$validator = Validator::make($request->all(), [
"id" => 'required|integer'
]);
}
But validation rule does not work for $id parameter. How to validate that?
It's not particular to put, its particular to any route parameter. This is because route params not included in the all() collection.
public function accept(Request $request, $id)
{
$validator = Validator::make(array_merge(
[
'id'=>$id
],
$request->all()
), [
"id" => 'required|integer'
]);
}