Phoenix
Phoenix

Reputation: 322

How to use unique validation in laravel?

I have comments table:

enter image description here

My Comment controller where its taking values from form and validating it and storing it in database.

public function store(Request $request, $product_id)
    {
        $this->validate($request, array(
            'name' => 'required',
            'email'=> 'required|email|unique:comments,product_id',
            'comment' => 'required',
            'rating' => 'required|integer'
            ));
        $product = Product::find($product_id);
        $comment = new Comment();
        $comment->name = $request->name;
        $comment->email = $request->email;
        $comment->comment = $request->comment;
        $comment->rating = $request->rating;
        $comment->product()->associate($product);

        $comment->save();
        Session::flash('success','Comment was added');
        return redirect()->route('product.show',[$product->id]);
    }

I am trying to validate such that only unique email id is allowed to comment on every product_id that is if user has already commented on product_id 1 then the same user is not allowed to comment again on that id.

I tried

'email'=> 'required|email|unique:comments,product_id'

But as u can see about same email id data was entered for same product_id.

A user can comment on n number of product_id page but cannot comment again once he has commented on that id.

Is there a way to validate if email data has been entered in database for particular product_id then the same email is not allowed to submit the form.

enter image description here

If different product_id then email can enter.

Thanks.

Upvotes: 6

Views: 5368

Answers (5)

Saumini Navaratnam
Saumini Navaratnam

Reputation: 8860

You can use the validation rule unique. Reference

use Illuminate\Validation\Rule;

$this->validate($request, array(
     'name' => 'required',
     'email'=> ['required', 'email', Rule::unique('comments', 'email')->where(function($query) {
                    $query->where('product_id', $product_id);
               })],
     ...
));

Hope this will help you

Upvotes: 0

prateekkathal
prateekkathal

Reputation: 3582

Write this in your console

php artisan make:provider ValidationServiceProvider

Then replace your App\Providers\ValidationServiceProvider with

namespace App\Providers;

use Validator;
use App\Comment;
use Illuminate\Support\ServiceProvider;

class ValidationServiceProvider extends ServiceProvider
{
  /**
   * Bootstrap any application services.
   *
   * @return void
   */
  public function boot() {
    Validator::extend('unique_email_comment', function($attribute, $value, $parameters, $validator) {
      return !Comment::where('email', $value)->where('product_id', $parameters[0])->exists();
    });
  }

  /**
   * Register the service provider.
   *
   * @return void
   */
  public function register() {
    //
  }
}

Note :- Please ensure the Model App\Comment is replaced with the namespace of the modal you use for your comments system.

Now add it to providers in config/app.php like

App\Providers\ValidationServiceProvider::class,

Now, you can validate the existence of the row by:

'email' => 'unique_email_comment:' . $productId;

// or
// 'email' => 'unique_email_comment:' . request()->get('product_id');

You can also add a custom message like this

return [
  'email.unique_email_comment' => 'A comment has already been made for this product with the email provided';
]

Please note that I haven't tested the code out but this should work if all the data is passed correctly and all namespaces are correctly used.

Upvotes: 2

Parth Vora
Parth Vora

Reputation: 4114

There is no way that you can use multiple columns for the unique rule. You have to manually check that by firing a query.

Upvotes: 0

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

Have you try unique_with custom validation. May be this package with full fill your requirement. You can check and get example here.

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163948

This is not how unique rule works. For your task you need to create custom validation rule and check manually if user with this email had already commented this product.

https://laravel.com/docs/5.3/validation#custom-validation-rules

Upvotes: 0

Related Questions