There are many ways to achive this and each will have pros and cons. The following might be a bit advanced if you are totally new to Laravel, but I'm sure that you will grasp the idea if you take a look to the documentation, as it's pretty easy to understand and intuitive.
I'll suggest you to:
- Create a custom validation rule to use in your controller
- Declare this custom validation in a service provider
- Use it in your controller
Create a custom validation rule
Imagine you want to check if certain input value is an actual arithmetic operator. There are many ways to do this in PHP. Here a few:
if($value == '+' || $value == '-' || $value == '*' || $value '/')
{
// It IS a valid operator
}
Another way, as suggested in above comments is to use a switch:
switch($value)
{
case '+':
case '-':
case '*':
case '/':
// it IS a valid operator
break;
default:
// otherwise, it is NOT
}
I personally prefer a lookup in array:
in_array($value, ['+', '-', '*', '/']);
Of course, there may exist many other ways.
Feel free to adopt the one that turns out to be clearer to you and you'll be able to refactor later as you learn more programming techniques.
So now that you can distinguish an operator from anything else, you can make use of a custom validation rule that implements this code:
Validator::extend('operator', function ($attribute, $value, $parameters, $validator) {
return in_array($value, ['+', '-', '*', '/']);
});
Note that we have called it operator
, but you can pick any name of your will. Try to keep it clean and intuitive. A few alternatives: valid_operator
, arithmetic_operator
, etc.
Declare the rule in a service provider
But in order to actually use the rule, you need to execute this code somewhere. A good place to start is in the boot()
method of a service provider. You can use your AppServiceProvider
, and you can always move it somewhere else (i.e. a more dedicated service provider) as you learn how to structure your application.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Validator::extend('operator', function ($attribute, $value, $parameters, $validator) {
return in_array($value, ['+', '-', '*', '/']);
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}
Use it in controller
As you now have your custom rule you can use it like this:
$this->validate($request, ['text'=> 'required|operator']);
Final words: Remember this is not the only way to do it. It is one of the possible options that Laravel suggests from it's documentation. In the end, it's always up to you. Try to understand each piece, always read the documentation as it's very helpful, and try to split your problem into steps. Code the least that works for you and always consider an I'll be back for refactor.