murilo

Form Validation Rule when Updating pass ID value

Posted 1 month ago by murilo

hello , I have a a question about form Validation Rule . Can I pass more than one value to this class ? My Rule validation class , verify -

IF IS CREATING -
* If it has NOT other product with the same title .

IF IS UPDATING -
* If it has NOT other product with the same title .
* if is the same ID of the product that I am updating  , IT will not verify if has the same title of that product .

I wold Like to pass the ID , when I update .

I have form request like this -


use App\Rules\VerifyTitleExists;

... 

 public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title'               => [ 'required' , new VerifyTitleExists ] ,
            'price'               => 'required' ,
            'category_id'         => 'required' ,
        ];
    }

And a Rule Validation -

use App\Product;

     public function __construct()
    {
        //
    }

    public function passes($attribute, $value)
    {
    
    // how could I get this $id value ?         

    // IT IS UPDATING 
    if($id){

           return Product::where('title' , $value)->where('id' , '!', $id)->first() ?  false
                                                                                                  :  true;  

    }

    // IS CREATING
        // IF TITLE EXISTS RETURN FALSE
        return Product::where('title' , $value)->first() ?  false
                                                                           :  true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'This Title  Already Exists , Chose Another One ';
    }


WHat wold be the best whay to do that ? It is that possible to send the ID value to the Rule Class ?

Thanks

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.