validating inputs in Laravel 5.8 - laravel-5

I am trying to validate input quantity of an item in Laravel. How will I do this using request()->validate([])? I want to validate if the input quantity from user is greater than the quantity of item from database.
Also, is it possible to return an error message if the entered quantity is greater than the quantity from database?
Here's my validation, I know this is wrong.
public function deduct(Request $request)
{
$item = Inventory::findOrFail($request->itemid);
request()->validate([
'quantity' => $item->quantity > $request->quantity
]);
}

You can use min, max and digits_between
$rules = ['test' => 'digits_between:2,5'];
or
$rules = ['test' => 'numeric|min:2|max:5'];

Set $item->quantity is the minimum value.
public function deduct(Request $request)
{
$item = Inventory::findOrFail($request->itemid);
$validatedData = $request->validate([
'quantity' => 'min:'.(int)$item->quantity
]);
}

Related

server side validation of dynamics inputs - laracast

I've a form where user can update name and rate. Here user can dynamically add the inputs as well so that they can send multiple items at once. But I wonder how to validate them.
controller:
public function store(Request $request)
{
//how to validate name and rate so that they are not empty & name should be unique here?
if ($request->get('name')) {
foreach ($request->get('name') as $key => $value) {
ItemType::create([
'name' => $request->get('name')[$key],
'rate' => $request->get('rate')[$key],
]);
}
}
return redirect()->back();
}
Generally the validation is done as below but how to implement in above scenario for dynamic inputs?
$request->validate([
'name' => 'required|unique:name',
'rate' => 'required',
]);
thanks in advance

Laravel form request validation on store and update use same validation

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;
}

laravel / How to store the random number with the requests in the database

I have a field in the in_out model that I want to insert with the requests in the database?
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:255',
'type' => 'required|max:255',
]);
$add = in_out::create($validatedData);
}
Your question is very difficult to understand.
This is an implementation in case you want to add attributes after validation and before storing on DB.
use App\InOut;
class InOutController
{
...
public function store(\Request $request)
{
$rules = [
'name' => 'required|string|max:255',
'type' => 'required|string|max:255',
];
$attributes = $request->validate($rules);
$attributes['description'] = 'Adding a description after validation and before store on database';
$inOut = InOut::create($attributes);
return redirect('/inout')->with('inOut', $inOut)->with('status', 'InOut created.');
}
...
}

Update two tables using one function in Laravel

I'm building an app using Laravel 5.7 and Vue.js2. I have two tables: departments and users. A user can be a chief of a department. I made the relationship between the models. I want it so that when I create a new department, the type of the chief will be changed on the user's table to 'chief.'
DepartmentController
public function store(Request $request)
{
$this->validate($request, [
'name' => 'string|required|max:191',
'bio' => 'string|required',
'user_id' => 'integer|required|unique:departements'
]);
return Department::create([
'name' => $request['name'],
'user_id' => $request['user_id'],
'bio' => $request['bio']
]);
}
Can you try this.
Controller
public function store(Request $request)
{
$this->validate($request,[
'name'=>'string|required|max:191',
'bio'=>'string|required',
'user_id'=>'integer|required|unique:departements'
]);
$new_department = Department::create([
'name'=>$request['name'],
'user_id'=>$request['user_id'],
'bio'=>$request['bio']
]);
$get_user = User::where('id', $request['user_id'])->first();
if($get_user)
{
$get_user->type = 'chief';
$get_user->save();
}
return ['message' => 'success'];
}
In this code, After saving the New Department I get the UserData in UserModel where id is the $request['user_id] then check it if exists.
If exists, I change the type to 'chief' and save.
If you have relationship between two models then you can update like this
$product = Department::with('relationship_function_name')->find($id);
$product->fields= $request->input_name;
$product->relationship_function_name->field_name = $request->input_name;
$product->update();
Hope this helps :)

Laravel validation differences on update and save

I'm using Jeffrey Way's model validation (https://github.com/JeffreyWay/Laravel-Model-Validation) to validate both on save and update. With this method, let's say you fill a update some fields on an entry, then call the save() method, the validation will run on all the fields currently set on the entry. But if the validation requires a field, say the email address, to be unique, the validation will fail because it already exists:
User.php:
protected static $rules = [
'email' => 'required|email|unique:users',
'firstname' => 'required',
'lastname' => 'required'
];
Controller.php:
// Get user from id
$user = User::find($id);
// Update user
$user->update($data);
// Validation when model is saved, via Way\Database\Model
if ($user->save())
{
return Response::json([
'data' => $user->toArray()
], 200);
}
if ($user->hasErrors())
{
return Response::json([
'errors' => $user->getErrors()
]);
}
Will return errors because the email address failed the validation. So, with this method, how do you tell the validator to ignore the unique rule for the email?
I think I use similar behaviour with different approach. Using this model, I thing you shold override the validate method to get the rules from a custom method, in witch you could set your new rules for existing models.
Something like this could work:
protected function processRules($rules = array()) {
$result = [];
if (empty($rules)) {
$rules = static::$rules;
}
// Add unique except :id
$replace = ($this->exists()) ? ',' . $this->getKey() : '';
foreach ($rules as $key => $rule) {
$result[$key] = str_replace(',:' . $this->getKeyName(), $replace, $rule);
}
return $result;
}
And override your validate method to call the proccessRules method.
public function validate() {
$v = $this->validator->make($this->attributes, $this->processRules(static::$rules), static::$messages);
if ($v->passes()) {
return true;
}
$this->setErrors($v->messages());
return false;
}
So now, you can define your email rule as required|email|unique:users:id, and when its a new User the rule should be required|email|unique:users and when you update the User with id 1234 the rule will be required|email|unique:users:1234.
I hope it works fine for you.
I've had this problem! I decided the problem on their own.
protected static $rules = [
'email' => $user->email == Input::get('email') ? 'required|email' : 'required|email|unique:users',
'firstname' => 'required',
'lastname' => 'required'
];
You cannot do it using this package, because you need to pass id for the unique rule. You could do it this way:
protected static $rules = [
'email' => 'required|email|unique:users,email,{id}',
'firstname' => 'required',
'lastname' => 'required'
];
and extend this model to add your custom validation method to replace {id} with id attribute

Resources