Skip to content

Instantly share code, notes, and snippets.

@sworup
Created May 18, 2016 04:43
Show Gist options
  • Save sworup/07739f078a486b044a622be9b9cf46e9 to your computer and use it in GitHub Desktop.
Save sworup/07739f078a486b044a622be9b9cf46e9 to your computer and use it in GitHub Desktop.
Custom validation problem. The 'ip' never gets included in the request input object before it gets validated, hence the validation fails.
<?php
namespace App\Extentions;
use DB;
use Log;
use Illuminate\Validation\Validator;
class CustomValidation extends Validator {
public function validateUniqueWith($attribute, $value, $parameters, $validator)
{
$input = $this->data;
$result = DB::table($parameters[0])->where(function($query) use ($attribute, $value, $parameters, $input) {
$query->where($attribute, '=', $value);
for ($i=1; $i < count($parameters); $i++) {
$query->where($parameters[1], '=', $input[$parameters[1]]);
}
})->get();
return $result ? false : true;
}
}
<?php
namespace App\Providers;
use App\Extentions\CustomValidation;
use Carbon\Carbon;
use Debugbar;
use Illuminate\Support\ServiceProvider;
use Validator;
class CustomValidationRules extends ServiceProvider
{
public function boot()
{
// Need to override the default validator with our own validator
// We can do that by using the resolver function
$this->app->validator->resolver(
function ($translator, $data, $rules, $messages)
{
// This class will hold all our custom validations
return new CustomValidation($translator, $data, $rules, $messages);
}
);
}
public function register()
{
//
}
}
<?php
namespace App\Requests;
use App\Http\Requests\Request;
class ReportRequest extends Request
{
/**
* 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()
{
$this->addIP();
return [
'ip_address' => 'required|unique_with:abuse_report,item_id,item_type',
'item_id' => 'required|integer',
'reason' => 'required'
];
}
public function attributes()
{
return [
'item_id' => 'item ID',
];
}
public function messages()
{
return [
'item_id.unique_with' => 'Duplicate Report: The submitted report was a duplicate of an existing poll or comment report.'
];
}
protected function addIP()
{
$this->merge(
array(
'ip_address' => $this->ip()
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment