-1
Hey, hey, it’s okay!?
I have implemented a business rule in which I need to validate data, I have created an external repository to http folder and I am using the library prettus/Laravel-validation Composer to validate the data more easily, because well the problem occurs when I try to return the custom errors in which the metodo getMessage()
is returned an empty message, while the getMessagebag()
returns the default message from validator
. I wanted to know how I do to return the custom error message with this pattern I am using?
Controller:
The controller is not fully implemented yet.
<?php
namespace App\Http\Controllers\Sisten_site;
use App\Models\Data_users;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\UserService;
class UsersController extends Controller
{
protected $service;
public function __construct( UserService $service)
{
$this->service = $service;
}
public function create_user()
{
return view ("public_template.objects.new_user");
}
public function save_user(Request $request)
{
$request= $this->service->store($request->all());
$usuario=$request['message'];
dd($request);
}
}
User Service
<?php
namespace App\Services;
use \Prettus\Validator\Contracts\ValidatorInterface;
use App \Validators\UserValidator;
use App\Models\Data_users;
use App\Models\Users;
use \Prettus\Validator\Exceptions\ValidatorException;
use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;
class UserService
{
protected $validator;
public function __construct( UserValidator $validator)
{
$this->validator= $validator;
}
public function store($data)
{
try {
$this->validator->with($data)->passesOrFail( ValidatorInterface::RULE_CREATE );
$usuario= $this->salvando($data);
return [
'message'=>'Post created',
'data' => $usuario
];
}catch (ValidatorException $e ) {
return [
'error' =>false,
'message' =>$e->getMessage()
];
}
}
public function salvando($data){
$data_user=Data_users::Create($data);
$user=Users::Create($data);
$user->data_user()->associate($data_user);
$user->save();
}
}
Class for data validation.
<?php
namespace App\Validators;
use \Prettus\Validator\Contracts\ValidatorInterface;
use \Prettus\Validator\LaravelValidator;
class UserValidator extends LaravelValidator {
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'email_user' => 'required|unique:users,email_user',
],
ValidatorInterface::RULE_UPDATE => [
]
];
protected $retu = [*texto grifado*
'email_user' => 'Este email já existe',
];
}
DD
Hello @Everton Welcome to Sopt, we know that your intention is to help, however in the way that your answer this writing it fits better as a comment, try to improve it a little, for example: add an example of how he can apply this validation. = P
– Icaro Martins
Thanks for the tip @Icaro.
– Everton Teotonio