MizzatY
1 month ago
130
3
Laravel

Laravel conditional validation

Posted 1 month ago by MizzatY

I want to pass $params['user_id'] to $fieldValidations and check if the hour is unique for specific user_id not for all hours hour in the database table

I created a model post

class Post extends Model
{
    protected $fillable = ['user_id', 'hour'];
    public static $fieldValidations = [
        'user_id'  => 'required',
        'hour'      => 'required|date_format:Y-m-d H:i:s|unique:post,hour,NULL,user_id,'
    ];
}

and a controller post

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        $params = $request->all();
        $params['user_id'] = 12;  

        $validator = Validator::make($params, Post::$fieldValidations);
        if ($validator->fails()) {
            return Response::json($validator->errors()->all(), 422);
        }


    }
}

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