Skip to content

Instantly share code, notes, and snippets.

@yakserr
Created October 21, 2022 08:03
Show Gist options
  • Save yakserr/9d043c73c2c08cd2b4bd81d42e557d8d to your computer and use it in GitHub Desktop.
Save yakserr/9d043c73c2c08cd2b4bd81d42e557d8d to your computer and use it in GitHub Desktop.
Form validation in laravel
<?php
namespace App\Http\Requests\User;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;
class UpdateUserRequest 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<string, mixed>
*/
public function rules()
{
// method 1 - Condition using route name
if (request()->routeIs('user.settings.store')) {
$passwordRule = 'required';
} elseif (request()->routeIs('user.settings.update')) {
$passwordRule = 'sometimes';
}
// $passwordRule = request()->routeIs('user.settings.store') ? 'required' : 'sometimes';
// method 2 - Condition using method name
if (request()->isMethod('POST')) {
$passwordRule = 'required';
} elseif (request()->isMethod('PUT')) {
$passwordRule = 'sometimes';
}
return [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users,email,' . request()->user()->id,
// method 1 & 2
'password' => [$passwordRule, Rules\Password::defaults()],
// method 3 - Rule When
'password' => [
Rule::when(request()->isMethod('POST'), 'required'),
Rule::when(request()->isMethod('PUT'), 'sometimes'),
'confirmed',
Rules\Password::defaults()
],
];
}
/**
* If password is not required, remove it from the request and cannot sent as null
*
*/
public function prepareForValidation()
{
if ($this->password == null) {
$this->request->remove('password');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment