Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extracting Validation
<?php
namespace App\Http\Controllers;
use App\User;
use App\Validators\UserValidator;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Auth\Access\AuthorizationException;
class UserController
{
use AuthorizesRequests;
/**
* @param Request $request
*/
public function store(Request $request)
{
$this->authorize('add', User::class);
$data = (new UserValidator())->validate(
$request->all(),
$user = new User()
);
$user->fill($data)->save();
}
/**
* @param Request $request
* @param \App\user $user
*/
public function update(Request $request, User $user)
{
$this->authorize('update', $user);
$data = (new UserValidator())->validate(
$request->except($request->user()->is_admin ? null : 'is_admin'),
$user
);
$user->fill($data)->save();
}
}
<?php
namespace App\Validators;
use App\User;
use App\Rules\ValidLanguage;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
class UserValidator
{
/**
* @param \App\User $user
* @return array
*/
public function rules($user)
{
return [
'name' => [
$user->exists ? 'sometimes' : null,
'required',
'string',
'max:255'
],
'email' => [
$user->exists ? 'sometimes' : null,
'required',
'string',
'email',
'max:255',
Rule::unique('users', 'email')->ignore($user->exists ? $user->id : null)
],
'business_website' => [
$user->exists ? 'sometimes' : null,
'required',
'domain'
],
'password' => [
$user->exists ? 'sometimes' : null,
'required',
'string',
'min:8'
],
'language' => ['required']
'is_admin' => ['bool'],
];
}
/**
* @param array $data
* @param \App\user $user
* @return array
*/
public function validate($data, $user)
{
return validator($data, $this->rules($user))
->after(function ($validator) use ($data, $user) {
$this->validateBusinessEmail($validator, $data, $user);
})
->validate();
}
/**
* @param \Illuminate\Contracts\Validation\Validator $validator
* @param array $data
* @param \App\User $user
*/
protected function validateBusinessEmail($validator, $data, $user)
{
$email = $data['email'] ?? $user->email;
$businessWebsite = $data['business_website'] ?? $user->business_website;
if (! Str::endsWith($email, $businessWebsite)) {
$validator->errors()->add(
'email', 'Email is invalid, you must use your business domain'
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.