Can Laravel model validate the field data types(int,float,..etc) while inserting data? - laravel

My problem is that I'm using noSql for my database and Laravel for the backend.
I know that we can validate the data types in the request but this validates only the incoming request after that we might calculate or re-arrange the data type of a field and insert it. I want to prevent this insertion by checking the data types. Is there a way to implement this validation in model like fillable [] or casts [].

You could setup an Observer on that model and in the Observer's 'updating' method you could perform any type formatting or cleanup required.
Or if it's a real edge case you could call the Validator facade to define the keys/rules to check for and then pass your changed object to it? If Validator->fails() you could loop through Validator->errors() and apply corrections as needed.

Related

How to get columns of a model instance in Laravel?

Can I extract a specific column for a model instance in Laravel instead of using query methods statically? more clearly, instead of writing the code below:
MyModel::select('columnName')->where('id', $model->id)->first();
can we write?
$model->select('columnName');
Well, when you grab it from a model class, it is a Eloquent Object, and it has all attributes from the database.
But if you are talking about serializing that into an array or JSON everytime, then you need to modify your $visible array ;
if you wanna transform it for a specific case, then you need to do :
MyModel::select('columnName')->where('id', $model->id)->first()->pluck('columnName');

Fetch field value from another one in Laravel Nova

I am just about the implement my custom belongs to component that has a dynamic functionality, on the fly it needs to make a HTTP call to the server and pass it few values, I need to pass it a value from another BelongsTo dropdown. How can this be achieved in Laravel Nova? Of course i can see which element has this value, but was wondered if there is a smarter way.

Why does Laravel array cast sort the elements, and can it be avoided?

I have a JSON field in a database which is populated using the array cast on an Eloquent model.
Before saving the field, Laravel sorts the elements by their key. Presumably this happens during serialisation.
Why does it do this? And is there a way to prevent it?
If you do not need to implement search by field, you can use the text type instead of the json type. Just before saving, you will need to execute json_encode, either yourself or implement a mutator.
I've never encountered this behavior before, but perhaps you can try using an accessor and a mutator to accomplish what you want. Let's say your database column is meta. You can use Laravel's special setAttribute and getAttribute methods in your model.
A mutator
For example, to json_encode data as it's about to be saved to your database it would be:
public function setMetaAttribute($value)
{
$this->attributes['meta'] = json_encode($value);
}
An accessor
To json_decode data as it's being retrieved it would be:
public function getMetaAttribute($value)
{
return json_decode($value, true);
}
The rule of thumb is take get or set and append your column name with first letters uppercased and removing any underscores, and appending Attribute to the method name. E.g. active_users column becomes getActiveUsersAttribute and so on.
Try that and see if it does any funky sorting.
Sometimes MySQL changes the order of keys when a JSON field is used.
The basic solution is to use a TEXT field to store json.
See Mysql 5.7 native json support - control keys order in json_insert function

ASP.NET MVC 3 Pattern for dynamic validation attributes including client side

My validation requirements for a the fields in a form are contained in an external table so that they can be updated without altering and rebuilding the code.
I have approximatley 100 fields with a mixture of validation requirements - range, required, regular expression and dependency on other fields. One example is date range validation. A date of birth field requires a date range which is between -10 years and -50 years of the current date.
I have read around the subject but have not identified a pattern for the complete solution.
I am using Visual Studio 2010 with MVC 3 and Entity Framework.
Any help with this would be gratefully received. Thanks in advance.
In a simple level I think you can still use the built-in Data-Annotations validation attributes to does the validation and for that you should map the validation rules stored in the table to the attributes.
I think all you have to do is create a custom model validation provider by inheriting the class ModelValidatorProvider. This class contains a single method called GetValidators that returns the collection validators for that model.
You have to implement the GetValidators method and in there you have to make a database call to get the validation rules for the model from the database (or from cache?) and convert them into ModelValidators. You could still use the built-in DataAnnotationsModelValidator to do the validations.
I would suggest you to look into the source code of DataAnnotationsModelValidatorProvider that will give you all the information. In that class what they are doing is basically iterating all the validation attributes applied to the model properties and converting them into ModelValidators through adapters and factories. In your case instead of attributes they are stored as records in tables and I don't think much work will be there.

Custom Data Annotation Attribute using Metadata

My requirement is to create a custom data annotation attribute for my project. The requirement is to validate the min/ max length of a specific product from the database, which will be retrieved from the database using the ProductID. I have a dynamic page for each product where there are two fields called max length & min length. User inputs the values in these two fields which needs to be validated from the database. Product table contains all the products & one will be selected by passing a productId.
Please suggest some pointers to implement the above.
Thanks in advance.
This validation you can do only in the server side and not in client, so I see two options.
Remote Validation - You can use remote validation when you want to perform the validation and show the error message through ajax.
IValidatableObject - By implementing this interface in the class you can do both the validations at the same time and return all the validation error messages as a collection. By this way the validation will happen after the form is normally submitted.

Resources