I have a Laravel User model which has a unique validation rule on username and email. In my Repository, when I update the model, I revalidate the fields, so as to not have a problem with required rule validation:
public function update($id, $data) {
$user = $this->findById($id);
$user->fill($data);
$this->validate($user->toArray());
$user->save();
return $user;
}
This fails in testing with:
ValidationException: {"username":["The username has already been
taken."],"email":["The email has already been taken."]}
Is there a way of fixing this elegantly?
Append the id of the instance currently being updated to the validator.
Pass the id of your instance to ignore the unique validator.
In the validator, use a parameter to detect if you are updating or creating the resource.
If updating, force the unique rule to ignore a given id:
//rules
'email' => 'unique:users,email_address,' . $userId,
If creating, proceed as usual:
//rules
'email' => 'unique:users,email_address',
Another elegant way...
In your model, create a static function:
public static function rules ($id=0, $merge=[]) {
return array_merge(
[
'username' => 'required|min:3|max:12|unique:users,username' . ($id ? ",$id" : ''),
'email' => 'required|email|unique:member'. ($id ? ",id,$id" : ''),
'firstname' => 'required|min:2',
'lastname' => 'required|min:2',
...
],
$merge);
}
Validation on create:
$validator = Validator::make($input, User::rules());
Validation on update:
$validator = Validator::make($input, User::rules($id));
Validation on update, with some additional rules:
$extend_rules = [
'password' => 'required|min:6|same:password_again',
'password_again' => 'required'
];
$validator = Validator::make($input, User::rules($id, $extend_rules));
Nice.
Working within my question:
public function update($id, $data) {
$user = $this->findById($id);
$user->fill($data);
$this->validate($user->toArray(), $id);
$user->save();
return $user;
}
public function validate($data, $id=null) {
$rules = User::$rules;
if ($id !== null) {
$rules['username'] .= ",$id";
$rules['email'] .= ",$id";
}
$validation = Validator::make($data, $rules);
if ($validation->fails()) {
throw new ValidationException($validation);
}
return true;
}
is what I did, based on the accepted answer above.
EDIT: With Form Requests, everything is made simpler:
<?php namespace App\Http\Requests;
class UpdateUserRequest extends Request
{
/**
* 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 [
'name' => 'required|unique:users,username,'.$this->id,
'email' => 'required|unique:users,email,'.$this->id,
];
}
}
You just need to pass the UpdateUserRequest to your update method, and be sure to POST the model id.
Unique Validation With Different Column ID In Laravel
'UserEmail'=>"required|email|unique:users,UserEmail,$userID,UserID"
or what you could do in your Form Request is (for Laravel 5.3+)
public function rules()
{
return [
'email' => 'required|email|unique:users,email,'. $this->user
//here user is users/{user} from resource's route url
];
}
i've done it in Laravel 5.6 and it worked.
'email' => [
'required',
Rule::exists('staff')->where(function ($query) {
$query->where('account_id', 1);
}),
],
'email' => [
'required',
Rule::unique('users')->ignore($user->id)->where(function ($query) {
$query->where('account_id', 1);
})
],
Laravel 5 compatible and generic way:
I just had the same problem and solved it in a generic way. If you create an item it uses the default rules, if you update an item it will check your rules for :unique and insert an exclude automatically (if needed).
Create a BaseModel class and let all your models inherit from it:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model {
/**
* The validation rules for this model
*
* #var array
*/
protected static $rules = [];
/**
* Return model validation rules
*
* #return array
*/
public static function getRules() {
return static::$rules;
}
/**
* Return model validation rules for an update
* Add exception to :unique validations where necessary
* That means: enforce unique if a unique field changed.
* But relax unique if a unique field did not change
*
* #return array;
*/
public function getUpdateRules() {
$updateRules = [];
foreach(self::getRules() as $field => $rule) {
$newRule = [];
// Split rule up into parts
$ruleParts = explode('|',$rule);
// Check each part for unique
foreach($ruleParts as $part) {
if(strpos($part,'unique:') === 0) {
// Check if field was unchanged
if ( ! $this->isDirty($field)) {
// Field did not change, make exception for this model
$part = $part . ',' . $field . ',' . $this->getAttribute($field) . ',' . $field;
}
}
// All other go directly back to the newRule Array
$newRule[] = $part;
}
// Add newRule to updateRules
$updateRules[$field] = join('|', $newRule);
}
return $updateRules;
}
}
You now define your rules in your model like you are used to:
protected static $rules = [
'name' => 'required|alpha|unique:roles',
'displayName' => 'required|alpha_dash',
'permissions' => 'array',
];
And validate them in your Controller. If the model does not validate, it will automatically redirect back to the form with the corresponding validation errors. If no validation errors occurred it will continue to execute the code after it.
public function postCreate(Request $request)
{
// Validate
$this->validate($request, Role::getRules());
// Validation successful -> create role
Role::create($request->all());
return redirect()->route('admin.role.index');
}
public function postEdit(Request $request, Role $role)
{
// Validate
$this->validate($request, $role->getUpdateRules());
// Validation successful -> update role
$role->update($request->input());
return redirect()->route('admin.role.index');
}
That's it! :) Note that on creation we call Role::getRules() and on edit we call $role->getUpdateRules().
I have BaseModel class, so I needed something more generic.
//app/BaseModel.php
public function rules()
{
return $rules = [];
}
public function isValid($id = '')
{
$validation = Validator::make($this->attributes, $this->rules($id));
if($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
In user class let's suppose I need only email and name to be validated:
//app/User.php
//User extends BaseModel
public function rules($id = '')
{
$rules = [
'name' => 'required|min:3',
'email' => 'required|email|unique:users,email',
'password' => 'required|alpha_num|between:6,12',
'password_confirmation' => 'same:password|required|alpha_num|between:6,12',
];
if(!empty($id))
{
$rules['email'].= ",$id";
unset($rules['password']);
unset($rules['password_confirmation']);
}
return $rules;
}
I tested this with phpunit and works fine.
//tests/models/UserTest.php
public function testUpdateExistingUser()
{
$user = User::find(1);
$result = $user->id;
$this->assertEquals(true, $result);
$user->name = 'test update';
$user->email = 'ddd#test.si';
$user->save();
$this->assertTrue($user->isValid($user->id), 'Expected to pass');
}
I hope will help someone, even if for getting a better idea. Thanks for sharing yours as well.
(tested on Laravel 5.0)
A simple example for roles update
// model/User.php
class User extends Eloquent
{
public static function rolesUpdate($id)
{
return array(
'username' => 'required|alpha_dash|unique:users,username,' . $id,
'email' => 'required|email|unique:users,email,'. $id,
'password' => 'between:4,11',
);
}
}
.
// controllers/UsersControllers.php
class UsersController extends Controller
{
public function update($id)
{
$user = User::find($id);
$validation = Validator::make($input, User::rolesUpdate($user->id));
if ($validation->passes())
{
$user->update($input);
return Redirect::route('admin.user.show', $id);
}
return Redirect::route('admin.user.edit', $id)->withInput()->withErrors($validation);
}
}
If you have another column which is being used as foreign key or index then you have to specify that as well in the rule like this.
'phone' => [
"required",
"phone",
Rule::unique('shops')->ignore($shopId, 'id')->where(function ($query) {
$query->where('user_id', Auth::id());
}),
],
I am calling different validation classes for Store and Update. In my case I don't want to update every fields, so I have baseRules for common fields for Create and Edit. Add extra validation classes for each. I hope my example is helpful. I am using Laravel 4.
Model:
public static $baseRules = array(
'first_name' => 'required',
'last_name' => 'required',
'description' => 'required',
'description2' => 'required',
'phone' => 'required | numeric',
'video_link' => 'required | url',
'video_title' => 'required | max:87',
'video_description' => 'required',
'sex' => 'in:M,F,B',
'title' => 'required'
);
public static function validate($data)
{
$createRule = static::$baseRules;
$createRule['email'] = 'required | email | unique:musicians';
$createRule['band'] = 'required | unique:musicians';
$createRule['style'] = 'required';
$createRule['instrument'] = 'required';
$createRule['myFile'] = 'required | image';
return Validator::make($data, $createRule);
}
public static function validateUpdate($data, $id)
{
$updateRule = static::$baseRules;
$updateRule['email'] = 'required | email | unique:musicians,email,' . $id;
$updateRule['band'] = 'required | unique:musicians,band,' . $id;
return Validator::make($data, $updateRule);
}
Controller:
Store method:
public function store()
{
$myInput = Input::all();
$validation = Musician::validate($myInput);
if($validation->fails())
{
$key = "errorMusician";
return Redirect::to('musician/create')
->withErrors($validation, 'musicain')
->withInput();
}
}
Update method:
public function update($id)
{
$myInput = Input::all();
$validation = Musician::validateUpdate($myInput, $id);
if($validation->fails())
{
$key = "error";
$message = $validation->messages();
return Redirect::to('musician/' . $id)
->withErrors($validation, 'musicain')
->withInput();
}
}
public static function custom_validation()
{
$rules = array('title' => 'required ','description' => 'required','status' => 'required',);
$messages = array('title.required' => 'The Title must be required','status.required' => 'The Status must be required','description.required' => 'The Description must be required',);
$validation = Validator::make(Input::all(), $rules, $messages);
return $validation;
}
I had the same problem.
What I've done: add in my view hidden field with id of a model and in validator check the unique, only if I've get some id from view.
$this->validate(
$request,
[
'index' => implode('|', ['required', $request->input('id') ? '' : 'unique:members']),
'name' => 'required',
'surname' => 'required',
]
);
You can trying code bellow
return [
'email' => 'required|email|max:255|unique:users,email,' .$this->get('id'),
'username' => 'required|alpha_dash|max:50|unique:users,username,'.$this->get('id'),
'password' => 'required|min:6',
'confirm-password' => 'required|same:password',
];
Laravel 5.8 simple and easy
you can do this all in a form request with quite nicely. . .
first make a field by which you can pass the id (invisible) in the normal edit form. i.e.,
<div class="form-group d-none">
<input class="form-control" name="id" type="text" value="{{ $example->id }}" >
</div>
...
Then be sure to add the Rule class to your form request like so:
use Illuminate\Validation\Rule;
... Add the Unique rule ignoring the current id like so:
public function rules()
{
return [
'example_field_1' => ['required', Rule::unique('example_table')->ignore($this->id)],
'example_field_2' => 'required',
];
... Finally type hint the form request in the update method the same as you would the store method, like so:
public function update(ExampleValidation $request, Examle $example)
{
$example->example_field_1 = $request->example_field_1;
...
$example->save();
$message = "The aircraft was successully updated";
return back()->with('status', $message);
}
This way you won't repeat code unnecessarily :-)
public function rules()
{
if ($this->method() == 'PUT') {
$post_id = $this->segment(3);
$rules = [
'post_title' => 'required|unique:posts,post_title,' . $post_id
];
} else {
$rules = [
'post_title' => 'required|unique:posts,post_title'
];
}
return $rules;
}
For a custom FormRequest and Laravel 5.7+ you can get the id of your updated model like this:
public function rules()
{
return [
'name' => 'required|min:5|max:255|unique:schools,name,'.\Request::instance()->id
];
}
For anyone using a Form request
In my case i tried all of the following none of them worked:
$this->id, $this->user->id, $this->user.
It was because i could not access the model $id nor the $id directly.
So i got the $id from a query using the same unique field i am trying to validate:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$id = YourModel::where('unique_field',$this->request->get('unique_field'))->value('id');
return [
'unique_field' => ['rule1','rule2',Rule::unique('yourTable')->ignore($id)],
];
}
It will work 100%
I have both case implement like One case is same form field in database table products and other is products_name is form field and in table, it's name is name, how we can validate and ignore that id while updating. I have encrypted that so i'm decrypted id, if you are encrypt then you will decrypt otherwise pass it as it's coming from the form.
$request->validate([
'product_code' => 'required|unique:products,product_code,'.decrypt($request->hiddenProductId),
'products_name' => 'required|unique:products,name,'.decrypt($request->hiddenProductId),
]);
there is detailed and straightforward answer to this question, I was looking for too
https://laravel.com/docs/9.x/validation#rule-unique
I have a dropdownlist with 2 items (Carrot & Lemon). I want to compare Carrot to Lemon. If it is a vegetable the add is validated or else it is blocked in the form.
In my code, the validation is not correct... My 2 values pass...
public function store(Request $request)
{
$this->validate($request, [
'vegetables' => 'required|min:3'
]);
$listVegetable = Exo::where('vegetables', $request->get('vegetables'))->count();
$word = "Carrot";
if ($listVegetable == $word){
Exo::create($request->all());
return redirect()->route('exos.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('exos.index')
->with('error', 'Not vegetable');
}
}
With $listVegetable = Exo::where('vegetables', $request->get('vegetables'))->count(); you get the amount of vegetables in your Database as Integer value. So your comparison with the carrot string does not make sense. You habe to write first() instead of count() and then I guess you need to access ->name property of this object, depending which rows your model has.
Ok, the main idea is verify if a string is into table, then you would take this way, just verify if string is into table:
public function store(Request $request)
{
$this->validate($request, [
'vegetables' => 'required|min:3'
]);
$vegetable = Exo::where('vegetables', $request->get('vegetables'))->first();
if ($vegetable){
Exo::create($request->all());
return redirect()->route('exos.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('exos.index')
->with('error', 'Not vegetable');
}
}
by other hand if you want to classify your Exo table, you'd need another colum, for example one called 'type', then the code looks like your main code(although it could be improved):
public function store(Request $request)
{
$this->validate($request, [
'vegetables' => 'required|min:3'
]);
$vegetable = Exo::where('vegetables', $request->get('vegetables'))->first();
$word = "vegetable";
if ($vegetable && $vegetable->type == $word){
Exo::create($request->all());
return redirect()->route('exos.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('exos.index')
->with('error', 'Not vegetable');
}
}
Hope this would help you.
I'm working on laravel 5.4 and I have this code:
public function apply($id){
$user = User::where('id', $id)->get()->first();
$data = [
'name' => $user->first_name,
'family' => $user->last_name,
'email' => $user->email,
'username' => $user->username,
'gender' => $user->gender,
'birthday' => $user->birthday,
'cv' => $user->cv,
'about' => $user->about,
'education' => $user->education,
'experiences' => $user->experiences,
];
$company = Company::get()->first();
Mail::send('emails.apply', $data, function ($message) use ($company)
{
$message->from('noreply#gmail.com', 'Robert Nicjoo');
$message->subject('New Apply');
$message->to($company->email);
});
Mail::send('emails.uapply', $data, function ($message) use ($user)
{
$message->from('noreply#gmail.com', 'Robert Nicjoo');
$message->subject('You Applied successfully');
$message->to($user->email);
});
Session::flash('success', 'Your application was sent to company.');
return redirect()->back()->with('session', $data);
}
This will send email to company when user click on apply button and send user info to them, now I also want to save data of the user include user_id, ad_id and company_id in another table so both user and company owners can have access to their history of applied ads.
I also have this table to save data on:
public function up()
{
Schema::create('applies', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('ad_id')->unsigned();
$table->integer('company_id')->unsigned();
$table->timestamps();
});
Schema::table('ads', function($table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('ad_id')->references('id')->on('ads');
$table->foreign('company_id')->references('company_id')->on('ads');
});
}
but in my controller (first codes) I need to know how to save those information in new table (second codes)?
Update:
Ad Model >>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ad extends Model
{
protected $fillable = [
'company_id', 'title', 'slug', 'image', 'description', 'address', 'job_title', 'salary',
];
public function company(){
return $this->belongsTo(Company::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
public function location(){
return $this->belongsTo(Location::class);
}
public function employment(){
return $this->belongsTo(Employment::class);
}
}
since your blade is like this:
<a class="btn btn-info btn-round" href="{{ route('apply.btn', Auth::user()->id) }}">
your route should look like
Route::get('apply/{id}', 'ApplyController#apply')->name('apply.btn');
why id only ? because in the discussion we had, i found out that ad_id and company_id was taken from the controller .. then in your controller this should work
public function apply($id)
{
$ad = Ad::first();
$company = Company::first();
$apply = new Apply();
$apply->user_id = $id
$apply->ad_id = $ad->id;
$apply->company_id = $company->id;
$apply->save();
// some more codes //
}
to avoid duplicates using user_id .. add a validation function like
function validateApply(array $data)
{
return Validator::make($data, [
'user_id' => 'required|numeric|unique:apply,user_id,NULL,id,ad_id,'.$data->ad_id,
]);
}
unique:apply - it means it will check the apply table the user_id already applied ..
then in the code above just do
$validateApply= $this->validateApply(['user_id'=>$id,'ad_id'=>$ad->id]);
if(!$validateApply->fails())
{
// do the above code here
}
else
{
// duplicate !!! so do your code here
}
then to retrieve the data assuming apply is already belongsTo the user as well the user hasOne apply
Auth::user()->apply->first()->somefield;
// im not sure how the hasOne works but try
Auth::user()->apply->somefield;
Your Route should be:
Route::post('apply/{$user_id}/{company_id}/{ad_id}','ApplyController#apply');
I think you have created model for ads.
So, simply save data like this:
Your function be like
public function apply(Request $request){
// other code
$apply = new Apply();
$apply->user_id = $request->user_id;
$apply->ad_id = $request->ad_id;
$apply->company_id = $request->company_id;
$apply->save();
// other code
}
And one more thing, You should have ad_id in your post request.
I have 2 tables that are in one to one relationship:
tours :
id|title|content
featured_image:
id|tour_id|name|path
My models FeaturedImage.php:
class FeaturedImage extends Model
{
public function tour()
{
return $this->hasOne('App\Tour');
}
}
Tour.php
class Tour extends Model
{
public function featuredimage()
{
return $this->belongsTo('App\FeaturedImage');
}
}
I want to save tour_id in featured_image table when tour is created. I'm using same form to fill tours table and to upload featured_image.
This is my store method looks like:
public function store(Request $request)
{
//validate the date
$this->validate($request, [
'title' => 'required|max:255',
'content' => 'required'
]);
//store the date
$tour = new Tour;
$tour->title = $request->title;
$tour->content = $request->trip_code;
$tour->save();
$featured_image= new FeaturedImage;
// save featured_image
if($request->hasFile('featured_image')){
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
$featured_image->path= $location;
$featured_image->tour()->associate($tour);
$featured_image->save();
}
//redirect to
Session::flash('success','Tour is successfully created !');
return redirect()->route('tours.show',$tour->id);
}
I'm successful to save data into tours table but unable to save in featured_image table. I 'm getting this error:
Call to undefined method Illuminate\Database\Query\Builder::associate()
I would be thankful if anyone can help me out.
You can user Mass Assignment to create your entries into DB like this:
$this->validate(request()->all(), [
'title' => 'required|max:255',
'content' => 'required'
]);
$tour_inputs = array_only(
$tour_inputs.
[
'title',
'content',
]
);
$tour = Tour::create($tour_inputs);
if($request->hasFile('featured_image')) {
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
$featuredImage = $tour->featuredImage()->save(new FeaturedImage([
'name' => $filename,
'path' => $location,
]));
}
Remember to define the $fillables inside your models, your models should look like this,
do check your relations, that you've made in the models, according to me they aren't correct:
class Tour extends Model
{
protected $fillables = [
'title',
'content',
];
public function featuredImage()
{
return $this->hasOne('App\FeaturedImage');
}
}
class FeaturedImage extends Model
{
protected $fillables = [
'name',
'path',
'tour_id',
];
public function tour()
{
return $this->belongsTo('App\Tour');
}
}
Hope this helps!
From your code the relationships that you have defined are in reverse order.
I mean logically, a Tour has one FeaturedImage and a FeaturedImage belongs to a Tour.
class Tour extends Model
{
//Mass Assignable fields for the model.
$fillable = ['title', 'content'];
public function featuredimage()
{
return $this->hasOne('App\FeaturedImage');
}
}
and
class FeaturedImage extends Model
{
//Mass Assignable fields for the model
$fillable = ['tour_id', 'name', 'path'];
public function tour()
{
return $this->belongsTo('App\Tour');
}
}
Then in your controller
public function store(Request $request)
{
//validate the data
$this->validate($request, [
'title' => 'required|max:255',
'content' => 'required'
]);
//store the data
$tour = Tour::firstOrCreate([ //protection against duplicate entry
'title' => $request->get('title'),
'content' => $request->get('trip_code')
]);
if($tour) //if the Tour exists then continue
{
// save featured_image
if($request->hasFile('featured_image')){
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
$featured_image = $tour->featuredimage()->create([
'path' => $location,
'name' => $filename //if you have this field on your FeaturedImage
}
//you could also have an else block to redirect back if the input doesn't have a file
//redirect to
Session::flash('success','Tour is successfully created !');
return redirect()->route('tours.show',$tour->id);
}
else
{
//if there occurs any error display the error message and redirect back - probably with validation errors or exception errors
Session::flash('error','Error message');
return redirect()->back()->withInput()->withErrors();
}
}
And don't forget to add the mass assignable fields to the $fillable array on your models.
UPDATE
For cases where a single form submission includes database transactions in multiple tables, you should use a try{}catch{} to ensure that either all related transactions run without any issue or neither of the transactions go through - to avoid data discrepancy.
You can rewrite your controller code as
public function store(Request $request)
{
//validate the data
$this->validate($request, [
'title' => 'required|max:255',
'content' => 'required'
]);
//store the data
//use the DB::beginTransaction() to manually control the transaction
//You would ideally want to persist the data to the database only if the input provided by the user
//has valid inputs for Tour as well as FeaturedImage, in case if any one invalid input you do not
//want to persist the data
DB::beginTransaction();
try
{
//firstOrCreate gives protection against duplicate entry for tour with same title and content
$tour = Tour::firstOrCreate([
'title' => $request->get('title'),
'content' => $request->get('trip_code')
]);
//proceed further only if $tour exists
if($tour)
{
// get featured_image
if($request->hasFile('featured_image')){
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
//save the featured_image
$featured_image = $tour->featuredimage()->create([
'path' => $location,
'name' => $filename //if you have this field on your FeaturedImage
}
}
}
catch(\ValidationException $e)
{
//In case of validation error, rollback the database transactions to avoid data discrepancy.
DB::rollBack();
$errors = $e->getMessage();
Session::flash('error', 'Whoops.. Please check the provided inputs');
return redirect()->back()->withInput()->withErrors['errors', $errors];
}
catch(\Exception $e)
{
//In case of any other error, rollback the database transactions to avoid data discrepancy.
DB::rollBack();
$errors = $e->getMessage();
Session::flash('error', 'Whoops.. Something went wrong. Please try again');
return redirect()->back()->withInput()->withErrors['errors', $errors];
}
//If both the transactions to the database i.e. saving the Tour as well as FeaturedImage ran without problem
//Commit to the database
DB::commit();
//redirect to
Session::flash('success','Tour is successfully created !');
return redirect()->route('tours.show',$tour->id);
}
Hope this helps.
order_id....product_id....product_quantity....created_at....updated_at
this is my pivot table...In my OrderRequest table I want to assign product_id as unique. But when I write like this;
public function rules()
{
return [
'product_id' => 'unique:order_product,product_id'
];
}
I encounter a problem. product_id becomes unique. but not only in an order, it becomes totally unique. I want to use this product_id in other orders but I can't. what can I do? How can I assign product_id as unique for each order_id values?
In your controller assuming that you call saveProducts method so :
function saveProducts($request){
validateProductList($request->input('product_list'))
$order->product()
->updateExistingPivot($product_id[$i],
array(
'product_quantity' => $product_quantity[$i],
'product_status' => $product_status[$i],
'updated_at' => Carbon::now() ));
// ....
}
function validateProductList($productIds){
if(isProductIdDuplicated($productIds)){
$error = 'You have a duplicated product in your Order, please edit it'
return redirectBack()-withError();
}
}
function isProductIdDuplicated($productIds){
$occureces_array = productIds();
foreach($productIds as $id){
if(++$occureces_array[$id] > 1){
return true;
}
}
return false;
}
And in your view you have access to this $error variable.
Thank you for your help. I have ended up the issue and it works now...
this is a part of my view;
<div class="grid1">
{!! Form::label('product_list'.$product_row, Lang::get('home.Select Product')) !!}
</div>
<div class="grid2 searchDrop">
{!! Form::select('product_list[]', $product_list, null, ['style'=>'width:150px;'])!!}
and this is part of my controller;
public function store(OrderRequest $request)
{
$order = Order::create( $request->all());
$product_list= $request->input('product_list');
$product_quantity = $request->input('product_quantity');
$product_status = $request->input('product_status' );
/* attach pivot table */
$order->product()->attach($product_list);
/* get the product list as array */
foreach($product_list as $key => $product_id)
{
$order->product()->updateExistingPivot($product_id, array(
'product_quantity' => $product_quantity[$key], // product_quantity is array
'product_status' => $product_status[$key], // product_status is array
'updated_at' => Carbon::now()
));
}
flash(Lang::get('home.The order has been created!'));
return redirect(url('/admin/orders/details',$order->id))->with('flash_message');
}
this is my OrderRequest;
public function rules()
{
return [
'customer_id' => 'required',
'product_quantity.*' =>'not_in:0',
'product_list' => 'product_unique', //custom validation in AppServiceProvider
];
}
and this is my AppServiceProvider;
public function boot()
{
Validator::extend('product_unique', function($attribute, $value, $parameters, $validator) {
if ( count(array_unique($value))!=count($value) ) {
return false;
}
return true;
});
}
Finally, in my validation.php I added;
"product_unique" => "Please select a product only once!",