I want to determine the field unique in laravel with the follow code:
This is the validation to the table product_subcategories:
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'name' => 'required|unique:product_subcategories|max:255',
'product_categories_id' => 'required'
],
ValidatorInterface::RULE_UPDATE => [
'id' => 'required',
'name' => 'required|unique:product_subcategories|max:255',
'product_categories_id' => 'required'
]
];
But I want that the field name be unique with the product_categories_id, for example, it cant be unique if the name of the field is the same but with product_categories_id is different each other. How can I do this?
You can specify the column to compare to with the second parameter of the rule.
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'name' => 'required|unique:product_subcategories,name|max:255',
'product_categories_id' => 'required'
],
ValidatorInterface::RULE_UPDATE => [
'id' => 'required',
'name' => 'required|unique:product_subcategories,name|max:255',
'product_categories_id' => 'required'
]
]
This example will be checking if there is any other field in product_subcategories with the same name.
For update, you can extend this with a third parameter which is the value of the name you want to ignore. (So you can save the SubCategory without changing it's name.)
Related
I'm building an API that takes in an array of 'additional_data' but I want some control over the fields that can be passed in.
Take the following JSON:
{
"name": "Joe Bloggs",
"additional_data": {
"type": "example",
"other_type": "example"
}
}
My current validation attempt:
return [
'name' => ['required'],
'additional_data.*' => ['sometimes', Rule::in(['type'])]
];
This always fails validation, what I'm looking for is to validate the key of the array so I can make sure the keys passed in are part of a 'whitelist'.
What you do now is you try to validate content of additional_data.type and additional_data.other_type.
You can do this by adding a custom validator. For example
Validator::extend('check_additional_data_keys', function($attribute, $value, $parameters, $validator) {
return is_array($value) && array_diff(array_keys($value), ['type', 'other_type']) === 0);
});
and use it inside your current rules
return [
'name' => ['required'],
'additional_data' => ['check_additional_data_keys'],
'additional_data.*' => ['required', 'string'],
];
Just specify your whitelist keys using the array validation rule:
return [
'name' => 'required',
'additional_data' => [
'sometimes',
'array:type',
],
];
1- In case you want applay same validation on all arrays' keys you can use the following:
return [
'name' => 'required',
'additional_data' => ['array', Rule::in(['type'])]
];
2- In case each key in the array needs different validation use the following:
return [
'name' => 'required',
'additional_data' => 'array',
'additional_data.ky1' => ['your validation here'],
'additional_data.ky2' => ['your validation here'],
];
I am building a Book Portal with Laravel. I have a unique validation rule on name to books.
$request->validate([
'name' => 'required|unique:books',
'about' => 'required',
'dsecription' => 'required',
'image' => 'required|mimes:jpeg,bmp,jpg,png|between:1, 6000',
'author_id' => 'required',
'publisher' => 'required',
'recommended' => 'required',
'epub_url' => 'required',
'year'=> 'required',
'pages' => 'required',
]);
I found out that an Author can have the same book name. Using unique on the name, will not allow me to upload.
I am thinking, if there is a way, I can check the author and the name of the book i.e
Check if the author has the same name, then apply the unique rule on name else upload.
I didn't find any solution for this. That's why I made my own custom validation like this :
$request->validate([
'name' => 'required|unique:books',
'author_id' => 'required',
// ...
]);
$data = Book::where('author_id', $request->author_id)->where('name', $request->name)->first();
if(!empty($data)) {
return redirect()->back()->withErrors('This name already taken'); // error message
}
You can try using the extra where conditions that can be passed to the unique rule to apply the unique constraint under certain conditions:
// we will make sure 'author_id' is an existing value
'author_id' => 'bail|required|integer|exists:authors,id',
'name' => [
'bail',
'required',
Rule::unique('books')
->where('author_id', (int) $request->input('author_id')),
],
Assuming author_id is on the books table.
Laravel 7.x Docs - Validation - Rules - unique
I have created a UserResource that is successfully returning all of my user attributes, including the organization it belongs to. It looks something like this:
Resources/User.php
return [
'type' => 'users',
'id' => (string)$this->id,
'attributes' => [
'name' => $this->name,
'email' => $this->email,
...
'relationships' => [
'organization' => $this->organization,
],
];
In my User model, there is a belongsTo relationship for User->Organization.
Instead of returning the actual organization model, I'd like to return the organization resource.
For example, an organization hasMany locations:
Resources/Organization.php
return [
'type' => 'organizations',
'id' => (string)$this->id,
'attributes' => [
'name' => $this->name,
...
'relationships' => [
'locations' => Location::collection($this->locations),
],
];
I can successfully return the collection of locations that belong to the organization. I have not been able to return a belongsTo relationship.
I've tried:
Resources/User.php
'relationships' => [
'organization' => Organization::collection($this->organization),
],
// or this
'relationships' => [
'organization' => Organization::class($this->organization),
],
// or this
use App\Http\Resources\Organization as OrganizationResource;
...
'relationships' => [
'organization' => OrganizationResource($this->organization),
],
How can I return a single model as a related resource? Thank you for any suggestions!
Have you tried it with the new keyword?
'relationships' => [
'organization' => new OrganizationResource($this->organization),
],
I am not able to add field which is not available in my database
I have tried adding
$this->crud->addFields([
[
'name' => 'coupon_type',
'label' => 'Coupon For',
'type' => 'select_from_array',
'options' => [
// Options
],
'allows_null' => true,
'default' => 1,
'attributes' => [
'id' => 'coupon_type'
]
]
]);
I want to add fields in my create page.
You can do this by defining accessors for your "virtual" attributes
public function getIsAdminAttribute()
{
return $this->attributes['admin'] == 'yes';
}
and defining the appends on your model
protected $appends = ['is_admin'];
Find everything in the docs here:
https://laravel.com/docs/5.8/eloquent-serialization#appending-values-to-json
This my request class rules.
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'unique:event_cals,eventDate,NULL,id,venue,$request->venue,time,$request->time'
];
I want to validate a rule like below.
'eventDate' && 'venue' && 'time' => 'unique'
There I need to check if there any row without same eventDate, venue and time altogether. Anyone knows how to declare such a rule?
This is the snapshot of db table.
Here is the possible solution:
<?php
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'event_date' => "unique:event_cals,event_date,NULL,id,venue,{$request->venue},time,{$request->time}",
];
I again want to highlight that; if you want that validator to work, you should make sure that the event_date and time should be correctly formatted.
An example unique check with additional wheres from our running project's update requests:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$id = $this->route('money');
return $rules = [
'name' => "required|string|min:3|max:255|unique:moneys,name,{$id},id,deleted_at,NULL,access,public",
];
}