Last active
March 22, 2020 15:24
-
-
Save elinardo10/9f2aaee291cd6b57f4a3c3a14a74cd56 to your computer and use it in GitHub Desktop.
Custom Validation Rules in State and Cities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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