Laravel validate array values contained in list - laravel

I am passing an array in a request to my api. Each value within the array must be within a pre-defined list.
If my list is: name,description,title
name, title //valid
different, title //invalid
I tried array|in:name,description,title but I think for that I can only pass a string.
Can I do this without using a custom rule?

Validate each string in the array:
'values.*' => 'string|in:name,title,description'

Have a look at "Validating Nested Array Input"
If I understand you correctly your validation rules should be (untested)
[
'*.name' => 'required|string',
'*.description' => 'required|string',
]
Maybe you also want to exclude unvalidated Keys

Related

Laravel Validation of Array

Laravel Help with validation
Hi everyone I want to validate an array of a foreign key to make sure it exists I am doing
'activities' => 'required|array',
'activities.*' => 'exists:admin_activities,id',
but it's skipping this validation
any solution for this
You can validate each element of an array in Laravel with "dot notation" to For example, to validate that each id in a given array input field is exists in admin_activities , you may do the following:
'activities.*.id' => 'required|exists:admin_activities,id',

Is it possible to get elements of array that failed validation in laravel

I have an array I want to validate, each element has an id field and it could also contain nested arrays, so I want to get all errors and if it's possible get elements that didn't pass validation.
I've tried to get all messages from validator $validator->messages()->all() but it return only messages from lowest level of arrays.
So if i pass something like this:
$object = [
'field1' => 'wont_pass_validation',
'id' => 0,
'nested_object' => [
'field2' => 'wont_pass_validation_either',
'id' => 1'
]
]
it will return only field2 message, without field1. If there is a way to get all messages and is it possible to get failed elements so I could extract id fields from them?

Laravel 5.4 different value validation rule in array

I have an input with an array of entities with an ID which must be unique
I've tried this:
'authors.*.id' => 'different:authors.*.id'
But it says 'The authors.0.id and authors.0.id must be different'
So what is a right way to validate this?
You want to use distinct rule.
When working with arrays, the field under validation must not have any duplicate values.
'foo.*.id' => 'distinct'

First Or Create

I know using:
User::firstOrCreate(array('name' => $input['name'], 'email' => $input['email'], 'password' => $input['password']));
Checks whether the user exists first, if not it creates it, but how does it check? Does it check on all the params provided or is there a way to specifiy a specific param, e.g. can I just check that the email address exists, and not the name - as two users may have the same name but their email address needs to be unique.
firstOrCreate() checks for all the arguments to be present before it finds a match. If not all arguments match, then a new instance of the model will be created.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) with only one item in the array. This will return the first item that matches, or create a new one if not matches are found.
The difference between firstOrCreate() and firstOrNew():
firstOrCreate() will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.
firstOrNew() will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save() on the model). Otherwise it will give you the matched item.
Choosing between one or the other depends on what you want to do. If you want to modify the model instance before it is saved for the first time (e.g. setting a name or some mandatory field), you should use firstOrNew(). If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate().
As of Laravel 5.3 it's possible to do this in one step with firstOrCreate using a second optional values parameter used only if a new record is created, and not for the initial search. It's explained in the documentation as follows:
The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model cannot be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument.
Example
$user = User::firstOrCreate([
'email' => 'dummy#domain.example'
], [
'firstName' => 'Taylor',
'lastName' => 'Otwell'
]);
This returns the User for the specified email if found, otherwise creates and returns a new user with the combined array of email, firstName, and lastName.
This technique requires Mass Assignment to be set up, either using the fillable or guarded properties to dictate which fields may be passed into the create call.
For this example the following would work (as a property of the User class):
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['email', 'firstName', 'lastName'];
firstOrCreate() checks for all the arguments to be present before it finds a match.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like:
$user = User::firstOrCreate([
'email' => 'abcd#gmail.com'
], [
'firstName' => 'abcd',
'lastName' => 'efgh',
'veristyName'=>'xyz',
]);
Then it checks only the email.
An update:
As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate method now accepts an optional second array as an argument.
The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:
See the Laravel API documentation
You can always check if in current instance the record is created with the help of
$user->wasRecentlyCreated
So basically you can
if($user->wasRecentlyCreated){
// do what you need to do here
}

Laravel: object or other structures (array, json..) to the view?

There are several ways you may pass data to a Laravel Blade view.
In this savvy discussion Laravel hidden attributes. e.g. Password - security Antonio Carlos Ribeiro states (and i agree) that:
"you are not supposed to send objects to a view. In the MVC pattern, views should receive data that are relative to them, processed data, not objects, because they don't have to know anything about your business logic."
I am learning Laravel and everywhere i look i often see examples like:
$users = User::all();
return View::make('users')->with('users', $users);
This one specially comes from the official documentation.
What method should be ideally used?
Do you transform your objects in array or other formats prior to send them to the view?
Do you selectively clean your data from all the unnecessary values prior of pass it to the template engine?
Apart being probably academically wrong, what are the potential risks for passing the object to the view?
If you use following approach
$users = User::all();
return View::make('users')->with('users', $users);
You will get a collection of User objects in your model and can use a loop to print out all the User objects and it's fine, what risk could be doing this, it's upon you, so you should know what should do but if you don't want to pass a collection object then it's also possible to pass only an array of arrays using:
$users = User::all()->toArray();
return View::make('users')->with('users', $users);
So, you'll get an array of arrays in the view where each child array will contain a perticular user's details. The array may look something like this:
array (size=2)
0 =>
array (size=5)
'id' => int 1
'username' => string 'heera' (length=5)
'email' => string 'heerasheikh#ymail.com' (length=21)
'created_at' => string '2014-01-20 06:10:53' (length=19)
'updated_at' => string '2014-01-23 10:23:50' (length=19)
1 =>
array (size=5)
'id' => int 2
'username' => string 'usman' (length=5)
'email' => string 'mdusyl#yahoo.com' (length=16)
'created_at' => string '2014-01-20 06:10:53' (length=19)
'updated_at' => string '2014-01-20 09:06:23' (length=19)
But, you can use the Laravel's traditional way and there is no risk at all. Don't follow something blindly, use your sense and ask yourself, what risk it may rise for you. You are only about to loop the collection, nothing else. Now, the choice is your's, if you pass the collection then you can use object notation, i.e. $user->username but if you pass an array then you have to use something like $user['username'], that's it.

Resources