Shiv Shankar Prasad
Shiv Shankar Prasad

Reputation: 157

how do i write the validation in the model in laravel?

When i validate the phone number i the controller then it is working but it increases the lines of code and i also have to write the callback functions, But i don't want to write the callbacks,instead i want to do it in the model, is there any way to do it??

'phone' =>['required',"regex:/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/",function($attribute, $value, $fail) use($id) {

                    if (strpos($value, "-") !== false) {
                        $exist = User::where([["phone", $value],["id","!=",$id]])->count();
                        if($exist){
                            $fail(ucwords($attribute).' is already taken.');
                        }else{
                            $result = User::where([["phone", str_replace("-","",$value)],["id","!=",$id]])->count();
                            ($result) ?  $fail(ucwords($attribute).' is already taken.') : "";
                        }

                    }else{
                        $exist = User::where([["phone", $value],["id","!=",$id]])->count();
                        if($exist){
                            $fail(ucwords($attribute).' is already taken.');
                        }
                    }
                },],

Upvotes: 0

Views: 440

Answers (2)

Helioarch
Helioarch

Reputation: 1188

I think you should be able define the function in your model as a static function that returns a closure, so then you can call it to get the closure and pass it on as a callback.

// In the model
public static function myValidationClosure($id){
   return function($attribute, $value, $fail)use($id) {
     if (strpos($value, "-") !== false) {
         $exist = User::where([["phone", $value],["id","!=",$id]])->count();
         if($exist){
             $fail(ucwords($attribute).' is already taken.');
         }else{
             $result = User::where([["phone", str_replace("-","",$value)],["id","!=",$id]])->count();
             ($result) ?  $fail(ucwords($attribute).' is already taken.') : "";
         }
     }else{
         $exist = User::where([["phone", $value],["id","!=",$id]])->count();
         if($exist){
             $fail(ucwords($attribute).' is already taken.');
         }
     }
   };
 }

Then you can use it in the validation as

'phone' =>['required',"regex:/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/", MyModelClass::myValidationClosure($id)]

Upvotes: 1

void
void

Reputation: 913

Always The Good Solution is For The Validation is Make a Custom Request which is seperate and easy to handle follow this =>

php artisan make:request CustomRequest

The Request:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\User;

class CustomRequest extends FormRequest
{
    /**
     * 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 [

            'phone'        => [
                                    'required',

                                    'min:10', 
                                    'max':10',             
                                    'regex:/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/',     

                                 ],

        ];
    }
}

It will provide you a default validation message but if you want to make a custom message the you can do by making message()

https://laravel.com/docs/7.x/validation

Hope It will help you!

Upvotes: 0

Related Questions