1

I have a table which holds post_types. When a user wants to search for post_types I must validate whatever they select from the form. I plan to allow them to search for specific one single type or ALL types at once (no plan to allow them multiple selection yet). So my select has something like this

['all' => 'all',
1 => 'User Post',
2 => 'Editor Post',
3 => .... etc]

My 'all' value is not exist in post_types table so a validation rule like exists:post_types,id would not work. How else can I do this?

2 Answers 2

1

How about to create your custom validation rule?

Validator::extend('availablePostTypes', function($attribute, $value,  $parameters, $validator) {
        $isAvailable = false;

        if ($value === 'all'){
            $isAvailable = true;
        }

        // query for existence
        else {
            $count = Post::where('type', $value)->count();
            $isAvailable = (0 < $count);
        }

        return $isAvailable;
    });

Finally, just call the rule:

$rules = [
    'post_types'=> ['availablePostTypes'],
];
Sign up to request clarification or add additional context in comments.

Comments

0

You haven't specified which Laravel version it is, so I'll suppose it's the latest stable one (5.1) at the time being.

Given we're in a controller method, you could do something along the lines of

public function foo(Request $request)
{

  if ($type = $request->post_type != 'all') 
  {
    $data = Post::whereType($type)->get();
  }
  else
  {
    $data = Post::all();
  }

  // the rest of your code

}

Please do note this is just a proof of concept, and you might delegate the same task to a different class if that's what you want.

Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.