how to detect if a field has input in laravel - php

I was trying to create a validation in laravel controller, where if one of the fields has input, then it will validate the rest of the fields to be 'required'. But it prompts Error
Class 'Illuminate\Support\Facades\Input' not found. Please help
if(Input::has('quantity1') || has('unit1') || has('dimension1') || has('price1')){
$data = $request->validate([
'quantity1' => 'required',
'unit1' => 'required',
'dimension1' => 'required',
'price1' => 'required',
]);

Use required_with laravel validation rule...
$data = $request->validate([
'quantity1' => 'required_with:unit1,dimension1,price1',
'unit1' => 'required_with:quantity1,dimension1,price1',
'dimension1' => 'required_with:quantity1,unit1,price1',
'price1' => 'required_with:quantity1,unit1,dimension1',
]);

Input is deprecated.
I would highly suggest creating a custom request class and using that.
The benfits include:
Conforming to SOLID principles.
Easy place to manage your rules and messages.
Easy place to handle permissions should you choose.
Can be extended and reused as needed.
--
Here are the steps how to do that:
Run php artisan make:request YourCustomRequestClassNamae
Fill the new app\Http\Requests\YourCustomRequestClassNamae.php file with:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class YourCustomRequestClassNamae 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 [
'quantity1' => 'required',
'unit1' => 'required',
'dimension1' => 'required',
'price1' => 'required',
];
}
}
In the controller do something like:
<?php
namespace App\Http\Controllers;
...
use App\Http\Requests\YourCustomRequestClassNamae;
...
class YourControllerName extends Controller
{
...
public function yourMethodName(YourCustomRequestClassNamae $request)
{
$validatedData = $request->validated();
...
If the validation above fails it will return back with a 422 and the messages automatically ready to be pulled from the message bag.
Sources:
https://laravel.com/docs/master/validation#form-request-validation
Example in the wild:
https://github.com/jeremykenedy/larablog/blob/master/app/Http/Requests/StoreTagRequest.php
https://github.com/jeremykenedy/larablog/blob/master/app/Http/Controllers/Admin/TagController.php#L7
https://github.com/jeremykenedy/larablog/blob/master/app/Http/Controllers/Admin/TagController.php#L56

Related

Unique always return already taken in laravel validation

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

Laravel dynamic validation

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',
];

How to pass non required fields through FormRequest?

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',
];
}

Laravel API Request Validation

Hello: I am writing an api with Laravel.
When I try to use request validation in the controller, I get a 405 method not allowed. When I remove the request validation, everything runs smoothly.
Here is my route:
Route::post('product/create', 'Api\v1\ProductController#create');
Here is my controller:
<?php
namespace App\Http\Controllers\Api\v1;
use App\Http\Requests\CreateProduct;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Handlers\Products;
use Illuminate\Support\MessageBag;
class ProductController extends Controller
{
/**
* Create Product.
*/
public function create(CreateProduct $request)
{
echo 'product created...';
}
}
Here is my request validator:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateProduct 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' => 'required',
'price' => 'required',
'short_description' => 'required'
];
}
/**
* Set custom validation messages.
*
* #return array
*/
public function messages()
{
return [
'title.required' => 'Please enter a title.',
'price.required' => 'Please enter a price.',
'short_description.required' => 'Please enter a short description.'
];
}
}
When I remove "CreateProduct $request" from the "create" method, everything works.
How can I use Laravel's request validation for api calls?
Set validation in Product Controller.
public function create(Request $request)
{
$rules=array(
'title' => 'required',
'price' => 'required',
'short_description' => 'required'
);
$messages=array(
'title.required' => 'Please enter a title.',
'price.required' => 'Please enter a price.',
'short_description.required' => 'Please enter a short description.'
);
$validator=Validator::make($request->all(),$rules,$messages);
if($validator->fails())
{
$messages=$validator->messages();
$errors=$messages->all();
return $this->respondWithError($errors,500);
}
echo 'product created...';
}
as #oseintow suggested:
if ($exception instanceof ValidationException) {
return response()->json(['errors'=>$exception->errors()], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
}
I had the same problem when I was testing my API with PostMan. It turns out I was using the wrong Headers (Accept and Content-Type should be application/json but instead I was using the application/x-www-form-urlencoded for Content-Type).
After correcting that the custom request was working just fine.
Add this to your exception > handler.php > render method
if($exception instanceof \Illuminate\Validation\ValidationException){}
return parent::render($request, $exception);
Hope it helps
just simply add ","
i think after this every thing run smoothly
this is how i use rules for code readability
https://pastebin.com/ivBEf7mT
public function rules()
{
return [
'title' => 'required',
'price' => 'required',
'short_description' => 'required',
];
}

Laravel custom request not found

I got my custom request RegisterRequest and I'm trying to use it but for some reason I always get this error like i'm not including it:
ReflectionException in RouteSignatureParameters.php line 25:
Class App\Http\Controllers\RegisterRequest does not exist
this is my request:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterRequest 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 [
'username' => 'required',
'email' => 'required',
'emailconfirm' => 'required',
'password' => 'required',
'passwordconfirm' => 'required',
];
}
public function messages(){
return [
'username.required' => 'Username is required',
],
}
}
and this is how i'm trying to use it:
use App\Http\Requests\RegisterRequest;
and in my method:
public function RegisterPost(RegisterRequest $request){
return response()->json($request->all(),200);
}
I always get 500 internal server error with message that request does not exists.
This command may help:
composer dump-autoload

Categories