Skip to content

Instantly share code, notes, and snippets.

@elinardo10
Last active March 22, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elinardo10/9f2aaee291cd6b57f4a3c3a14a74cd56 to your computer and use it in GitHub Desktop.
Save elinardo10/9f2aaee291cd6b57f4a3c3a14a74cd56 to your computer and use it in GitHub Desktop.
Custom Validation Rules in State and Cities
<?php
namespace App\V1\User\Rules;
use Illuminate\Contracts\Validation\Rule;
use App\V1\Common\Models\State;
use App\V1\Common\Models\City;
class belongstate implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public $stateId;
public function __construct($stateId)
{
$this->stateId = $stateId;
}
/**
* Determine if the validation rule passes.
*
* @param integer $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return City::where(['state_id' => $this->stateId, 'id' => $value])->exists();
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute não pertence ao estado selecionado';
}
}
<?php
namespace App\V1\User\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\V1\User\Rules\belongstate;
class UserUpdateRequest 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 [
'first_name' => 'required|string',
'last_name' => 'string|nullable',
'password' => 'min:6|sometimes',
'state_id' => 'integer|nullable|exists:states,id',
'city_id' => ['integer', 'nullable', new belongstate(request()->state_id)],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment