i have a problem with my production environnement.
In local i'm using php-cli and in production php-fpm and in production when $Response->send() is excecuted, i pass in the first if(\function_exists('fastcgi_finish_request'))) and this show me a white page instead of my render.
In my PublicController.php i have this :
#[Route('/user/validate/account', name: 'user_validate_account', methods: ['GET'])]
public function validateEmail(Request $request, SecurityService $securityService): Response
{
if($this->getUser() && $this->getUser()->getIsEmailVerified() && !$tokenRequested = $request->get('token')) return $this->redirectToRoute('public_home');
$securityService->forceLogout();
$session = $request->getSession();
$session->remove('_user_validate_account_security_token');
if($tokenRequested = $request->get('token')) {
$securityToken = $this->securityTokenRepository->findOneByToken($tokenRequested);
if(!$securityToken) {
$this->addFlash('globalInfo', "Le token de sécurité est invalide !");
return $this->redirectToRoute('public_user_validate_account');
} elseif($securityToken->getTokenType() === SecurityToken::_VALIDATION_EMAIL) {
if ($securityToken->getExpiresAt() < DateUtility::now()) {
$this->addFlash('globalInfo', "Votre token de sécurité à expiré, merci renouveler votre demande !");
$this->securityTokenRepository->remove($securityToken, true);
return $this->redirectToRoute('public_user_validate_account');
}
$securityToken->getUser()->setIsEmailVerified(true);
$this->securityTokenRepository->flush();
if ($securityToken->getUser()->getIsPasswordNeedToChange()) {
$session->set('_user_validate_account_security_token', $securityToken);
return $this->redirectToRoute('public_user_validate_password');
} else {
$this->addFlash('globalInfo', "Votre compte est vérifié, bonne gestion :)");
return $this->redirectToRoute('public_home');
}
}
}
return $this->render('security/user_validate/account.html.twig');
}
In local, with php cli when
$securityService->forceLogout();
is executed, script will continue and show my render. But in production i'm using php-fpm and i have a white page.
My $securityService->forceLogout(); use Response from HttpRequest of Symfony:
<?php
namespace App\Service;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Http\Event\LogoutEvent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class SecurityService
{
public function __construct(
private readonly RequestStack $requestStack,
private readonly EventDispatcherInterface $eventDispatcher,
private readonly TokenStorageInterface $tokenStorage
)
{}
public function forceLogout() : void
{
$logoutEvent = new LogoutEvent($this->requestStack->getCurrentRequest(), $this->tokenStorage->getToken());
$this->eventDispatcher->dispatch($logoutEvent);
$this->tokenStorage->setToken(null);
$response = new Response();
$response->headers->clearCookie('REMEMBERME');
$response->send();
}
}
When $response-send(); :
/**
* Sends HTTP headers and content.
*
* #return $this
*/
public function send(): static
{
$this->sendHeaders();
$this->sendContent();
if (\function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
} elseif (\function_exists('litespeed_finish_request')) {
litespeed_finish_request();
} elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
static::closeOutputBuffers(0, true);
flush();
}
return $this;
}
In production, i go to the 2nd elsif, and this show my page with my render, but in production i enter in the first if (\function_exists('fastcgi_finish_request')) and this show me a white page 200.
Someone can help me to fixe this please ?
Related
I am trying to setup google indexing api in codeigniter, I have done all steps on google cloud and search console part.
It works, but returning success message on all options event when url is not submited, that is why I want to get exact response from google instead of a created success message.
How can I display exact response from google return $stringBody;? or check for the correct response ?
Here is my controller :
namespace App\Controllers;
use App\Models\LanguageModel;
use App\Models\IndexingModel;
class IndexingController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->indexingModel = new IndexingModel();
}
public function GoogleUrl()
{
checkPermission('indexing_api');
$data['title'] = trans("indexing_api");
$data["selectedLangId"] = inputGet('lang');
if (empty($data["selectedLangId"])) {
$data["selectedLangId"] = $this->activeLang->id;
}
echo view('admin/includes/_header', $data);
echo view('admin/indexing_api', $data);
echo view('admin/includes/_footer');
}
/**
* indexing Tools Post
*/
public function indexingToolsPost()
{
checkPermission('indexing_api');
$slug = inputPost('slug');
$urltype = inputPost('urltype');
$val = \Config\Services::validation();
$val->setRule('slug', trans("slug"), 'required|max_length[500]');
if (!$this->validate(getValRules($val))) {
$this->session->setFlashdata('errors', $val->getErrors());
return redirect()->to(adminUrl('indexing_api?slug=' . cleanStr($slug)))->withInput();
} else {
$this->indexingModel->AddUrlToGoogle($slug, $urltype);
$this->session->setFlashdata('success', trans("msg_added"));
resetCacheDataOnChange();
return redirect()->to(adminUrl('indexing_api?slug=' . cleanStr($slug)));
}
$this->session->setFlashdata('error', trans("msg_error"));
return redirect()->to(adminUrl('indexing_api?slug=' . cleanStr($slug)))->withInput();
}
}
And This is my model :
namespace App\Models;
use CodeIgniter\Model;
use Google_Client;
class IndexingModel extends BaseModel {
public function AddUrlToGoogle($google_url, $Urltype){
require_once APPPATH . 'ThirdParty/google-api-php-client/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig(APPPATH . 'ThirdParty/google-api-php-client/xxxxxxxxx.json');
$client->addScope('https://www.googleapis.com/auth/indexing');
$httpClient = $client->authorize();
$endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';
$array = ['url' => $google_url, 'type' => $Urltype];
$content = json_encode($array);
$response = $httpClient->post($endpoint,['body' => $content]);
$body = $response->getBody();
$stringBody = (string)$body;
return $stringBody;
}
public function AddUrlToBing($google_url, $Urltype){
}
public function AddUrlToYandex($google_url, $Urltype){
}
}
This is a success response when I try it out of codeigniter and print_r($stringBody);
{ "urlNotificationMetadata": { "url": "https://example.com/some-text", "latestUpdate": { "url": "https://example.com/some-text", "type": "URL_UPDATED", "notifyTime": "2023-01-29T01:51:13.140372319Z" } } }
And this is an error response :
{ "error": { "code": 400, "message": "Unknown notification type. 'type' attribute is required.", "status": "INVALID_ARGUMENT" } }
But In codeigniter I get a text message "url submited" even if url not submited.
Currently you are not handling the actual response of IndexingModel->AddUrlToGoogle(). It seems your code has a validation before, so it claims, if no validation error occurs, its always a success.
So the first question to ask is, why your validation is not working here - or is it?
Secondly you could handle the actual response in any case:
IndexingController
class IndexingController extends BaseController
public function indexingToolsPost()
{
if (!$this->validate(getValRules($val))) {
// validation error
$this->session->setFlashdata('errors', $val->getErrors());
return redirect()->to(adminUrl('indexing_api?slug=' . cleanStr($slug)))->withInput();
} else {
// no validation error
$apiResponseBody = $this->indexingModel->AddUrlToGoogle($slug, $urltype);
if(array_key_exists('error', $apiResponseBody)) {
// its an error!
// either set the actual messsage
$this->session->setFlashdata('error', $apiResponseBody['error']['message']);
// OR translate it
$this->session->setFlashdata('error', trans($apiResponseBody['error']['message']));
} else {
// Its a success!
$this->session->setFlashdata('success', trans("msg_added"));
}
// ...
}
return redirect()->to(adminUrl('indexing_api?slug=' . cleanStr($slug)))->withInput();
}
And in the model, return the response as an array:
IndexingModel
public function AddUrlToGoogle($google_url, $Urltype) {
// ...
$response = $httpClient->post($endpoint,['body' => $content]);
return json_decode($response->getBody() ?? '', true); // return an array
}
When I run PHPUnit tests, there are some errors displayed in my console, even though these errors do not affect my tests (they all pass). And it is very annoying to see all these errors
displayed errors
I tried in phpunit.xml file add the following lines:
convertErrorsToExceptions="false"
convertNoticesToExceptions="false"
convertWarningsToExceptions="false"
but it didn't help. I am using:
PHPUNIT: 9.5
Symfony: 6.0
PHP: 8.1
My tests look like this:
/**
* #test
* #dataProvider editItemInvalidDataProvider
*/
public function should_not_edit_item_and_not_redirect_when_failure(
?string $itemName,
?string $itemSellIn,
?string $itemQuality
): void {
$this->loginUser();
$crawler = $this->client->request('POST', '/item/1/edit');
$button = $crawler->selectButton('edit-item');
$form = $button->form();
$form['item[name]']->setValue($itemName);
$form['item[sellIn]']->setValue($itemSellIn);
$form['item[quality]']->setValue($itemQuality);
$this->client->submit($form);
$this->assertResponseNotHasHeader('location');
}
/** #test */
public function should_return_403_when_not_logged_in_and_reaching_edit_page(): void
{
$this->client->request('GET', '/item/1/edit');
$this->assertResponseStatusCodeSame(403);
}
And the controller:
#[Route('/item/{id}/edit', name: 'item_edit')]
#[ParamConverter('item', class: Item::class)]
#[IsGranted('ROLE_ADMIN', statusCode: 403)]
public function edit(
?Item $item,
Request $request,
): Response {
if (!$item) {
$this->addFlash('error', 'No item found');
return $this->redirectToRoute('item_list');
}
$form = $this->createForm(ItemType::class, $item);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->entityManager->persist($item);
$this->entityManager->flush();
$this->addFlash('success', 'Item successfully edited!');
return $this->redirectToRoute('item_list');
}
return $this->render('item/edit.html.twig', [
'form' => $form->createView(),
]);
}
Any ideas on how to suppress those errors?
You can tell the client to not follow any redirects with the following config:
$this->client->request('POST', '/item/1/edit', [
'max_redirects' => 0,
]);
This should prevent some (maybe all) of your errors.
I've done a URL shortener app for my server side programming subject.
For fun I decided to deploy it on a web server, in this case the oracle free tier with an ubuntu server with apache, and I also adquired a public domain.
In my local environment all works fine using the symfony local server:
symfony server:start
But once I deployed the app the redirections doesn't work anymore.
All occur on the home page, the user types the URL to shortener( and the new 'endpoint'), Symfony validates the URL and if it's the case the new 'endpoint', then if all it's valid store the data and also in the home shows the new URL (ex. '/hjas8ab') that the user needs to paste it behind my domain (ex. mydomain.xyz/hjas8ab) and then Symfony checks that the 'endpoint' is associated to an URL in the database and redirects the user to that URL. And is in this step that the app deployed fails, even if I hardcode the URL to redirect.
So I think it's the Apache virtual host configuration, but I'm not sure.
Here is the code:
ShortenerController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class ShortenerController extends AbstractController
{
#[Route('/{url?}', name: 'shortener')]
public function index(?String $created, ?String $endpoint,?bool $autogenerated, ?String $url, Request $req): Response
{
if($_SERVER["REQUEST_METHOD"] === "GET" && !is_null($url) ){
return $this->forward('App\Controller\UrlAddressController::redirection', ['finalRedirection' => $url]);
}
if(!is_null($endpoint)){
return $this->render('shortener/index.html.twig', [
'created' => $created, 'endpoint' => $endpoint, 'autogenerated' => $autogenerated
]);
}
return $this->render('shortener/index.html.twig');
}
#[Route('/create/autogenerated', name: 'autogenerated')]
public function autogenerated(Request $req): Response
{
define('URL_PATTERN', "/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)(:[0-9]{0,5})?(#[\w]*)?((?:\/[\+~%\/.\w\-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[.\!\/\\w]*))?)/i");
$urlOriginal = $req->request->get('url');
$validUrl = preg_match(URL_PATTERN, $urlOriginal);
if($validUrl !== 1){
return $this->render('shortener/index.html.twig', ['invalidAutogenerated'=> 'La URL introducida no es valida.']);
}
$autogeneratedURL = bin2hex(random_bytes(6));
return $this->forward('App\Controller\UrlAddressController::createUrlAddress', ['urlEndpoint' => $autogeneratedURL, 'realUrl' => $urlOriginal, 'autogenerated' => true]);
}
#[Route('/create/custom', name: 'custom')]
public function custom(Request $req): Response
{
define('URL_PATTERN', "/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)(:[0-9]{0,5})?(#[\w]*)?((?:\/[\+~%\/.\w\-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[.\!\/\\w]*))?)/i");
define('ENDPOINT_PATTERN', "/^[A-Za-z0-9]{7,15}$/i");
$urlOriginal = $req->request->get('urlCustom');
$nuevaUrl = $req->request->get('endpoint');
$validUrl = preg_match(URL_PATTERN, $urlOriginal);
$validEndpoint = preg_match(ENDPOINT_PATTERN, $nuevaUrl);
if($validUrl !== 1){
return $this->render('shortener/index.html.twig', ['invalidCustom'=> 'La URL introducida no es valida.']);
}
if($validEndpoint !== 1){
return $this->render('shortener/index.html.twig', ['invalidEndPoint'=> 'La URL introducida no es valida. Solo caracteres alfanuméricos.']);
}
return $this->forward('App\Controller\UrlAddressController::createUrlAddress', ['urlEndpoint' => $nuevaUrl, 'realUrl' => $urlOriginal, 'autogenerated' => 0]);
}
}
UrlAddressController.php
<?php
namespace App\Controller;
use App\Entity\UrlAddress;
use App\Repository\UrlAddressRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Annotation\Route;
class UrlAddressController extends AbstractController
{
#[Route('/urlAddress', name: 'url_address')]
public function createUrlAddress(ManagerRegistry $doctrine, String $urlEndpoint, String $realUrl, bool $autogenerated): Response
{
$created = '';
$entityManager = $doctrine->getManager();
$newUrl = new UrlAddress();
$newUrl->setUrlEndpoint($urlEndpoint);
$newUrl->setRealUrl($realUrl);
$newUrl->setAutogenerated($autogenerated);
$entityManager->persist($newUrl);
$entityManager->flush();
if($autogenerated){
$created = "Hemos generado tu URL automáticamente con exito.";
}else{
$created = "Tu custom URL se ha creado con exito.";
}
return $this->forward('App\Controller\ShortenerController::index', [
'created' => $created,
'endpoint' => "/$urlEndpoint",
'autogenerated' => $autogenerated
]);
}
#[Route('/redirection', name: 'redirection')]
public function redirection(String $finalRedirection, ManagerRegistry $doctrine, Request $request): Response
{
$repository = $doctrine->getRepository(UrlAddress::class);
$url = $repository->findOneBy(['urlEndpoint'=> $finalRedirection]);
if(!$url){
// return new Response('No encontramos esa URL en nuestras bases de datos');
// return $this->forward('App\Controller\ShortenerController::index', [
// 'error' => 'No encontramos esa URL en nuestras bases de datos'
// ]);
$this->addFlash('error', 'No encontramos esa URL en nuestras bases de datos');
return $this->redirectToRoute('shortener');
}
$finalUrl = $url->getRealUrl();
if(str_split($finalUrl)[0] === 'h'){
return $this->redirect($finalUrl);
}else{
return $this->redirect('http://'.$finalUrl);
}
}
}
UrlAddres.php (Entity)
<?php
namespace App\Entity;
use App\Repository\UrlAddressRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: UrlAddressRepository::class)]
class UrlAddress
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'string', length: 255)]
private $urlEndpoint;
#[ORM\Column(type: 'string', length: 255)]
private $realUrl;
#[ORM\Column(type: 'boolean')]
private $autogenerated;
public function getId(): ?int
{
return $this->id;
}
public function getUrlEndpoint(): ?string
{
return $this->urlEndpoint;
}
public function setUrlEndpoint(string $urlEndpoint): self
{
$this->urlEndpoint = $urlEndpoint;
return $this;
}
public function getRealUrl(): ?string
{
return $this->realUrl;
}
public function setRealUrl(string $realUrl): self
{
$this->realUrl = $realUrl;
return $this;
}
The Apache virtual host configuration:
<VirtualHost *:80>
ServerName mydomain.xyz
ServerAlias www.mydomain.xyz
ServerAdmin webmaster#localhost
DocumentRoot /var/www/mydomain.xyz/public
<Directory /var/www/mydomain.xyz/public>
# enable the .htaccess rewrites
AllowOverride All
Order Allow,Deny
Allow from All
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
I´m trying to send an email confirmation when a contact form is submitted. So, I have a controller to do it and all it works fine.
The only problem is due to a textarea field which is making problems to me.
This is the output problem:
[previous exception] [object] (TypeError(code: 0): htmlspecialchars(): Argument #1 ($string) must be of type string, Illuminate\\Mail\\Message given at D:\\Proyectos\\PÁGINA PERSONAL\\profesional_website\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\helpers.php:118)
So, I'm debugging to check variable type and I checked that it was a string. I tried to parse such as strval($message) and concatenating such as trim($message." ") but it didn't work.
I attach controller code:
class EmailController extends Controller
{
function sendEmail (Request $request) {
Log::debug(gettype($request->description));
$formData = array(
'name' => $request->name,
'last_names' => $request->last_names,
'mail'=> $request->email,
'message'=> $request->description,
'phone' => $request->phone
);
Mail::to($formData['mail'])->send(new NotifyMail($formData));
if (Mail::failures()) {
$response['success'] = false;
$response['message'] = 'Ha ocurrido un error';
return $response;
}else{
$response['success'] = true;
$response['message'] = 'Mensaje enviado correctamente';
return $response;
}
}
}
And the blade view:
<div style="background-color:#ffcc66;text-align:center;padding:30px 0">
<h1 style="color: #fff;">¡Bienvenido a alexdevs, {{$name}}!</h1>
<p style="color: #fff;">Si este es tu problema:</p>
<p style="color: #fff;padding:20px 50px">{{$message}}</p>
<p style="color: #fff">¡Encontraremos una solución perfecta!</p>
<p style="color: #fff">Me pondré en contacto contigo lo antes posible a través de tu correo: {{$mail}}</p>
<h3 style="color: #fff;">¡Muchas gracias!</h3>
<img src="{{asset('img/negative_rounded_brand.png')}}" alt="alexdevs_logo"
style="height:50px;width:50px;margin-top:30px">
</div>
And this is the Mailable class:
class NotifyMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('mail.client', $this->data);
}
}
I have a problem that I can't find a solution, in reality 2 problems.
The first problem is the following, I made a custom validation rule to validate the "NIF" (identity used in Portugal), until this point everything is working, the validation rule is working, the problem is the message that is returning, the message is always "The given data was invalid." but "Invalid NIF" should appear.
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class NifValidator implements Rule
{
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$ignoreFirst = true;
$nif = trim($value);
\Log::info("Valida Rules NIF: " . $nif);
//Verificamos se é numérico e tem comprimento 9
if (!is_numeric($nif) || strlen($nif) != 9) {
return false;
} else {
$nifSplit = str_split($nif);
//O primeiro digíto tem de ser 1, 2, 5, 6, 8 ou 9
//Ou não, se optarmos por ignorar esta "regra"
if (
in_array($nifSplit[0], [1, 2, 5, 6, 8, 9])
||
$ignoreFirst
) {
//Calculamos o dígito de controlo
$checkDigit = 0;
for ($i = 0; $i < 8; $i++) {
$checkDigit += $nifSplit[$i] * (10 - $i - 1);
}
$checkDigit = 11 - ($checkDigit % 11);
//Se der 10 então o dígito de controlo tem de ser 0
if ($checkDigit >= 10) {
$checkDigit = 0;
}
//Comparamos com o último dígito
if ($checkDigit == $nifSplit[8]) {
\Log::info("VALIDA NIF TRUE");
return true;
} else {
\Log::info("VALIDA NIF False");
return false;
}
} else {
\Log::info("VALIDA NIF false");
return false;
}
}
}
public function validate($attribute, $value, $params)
{
return $this->passes($attribute, $value);
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return ':attribute inválido';
}
}
My AppServiceProvider.php
<?php
namespace App\Providers;
use Hyn\Tenancy\Environment;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
$env = app(Environment::class);
if ($fqdn = optional($env->hostname())->fqdn) {
config(['database.default' => 'tenant']);
}
// money format
Str::macro('money', function ($price) {
return number_format($price, 2, ',', '.');
});
\Validator::extend('nifvalidator', '\App\Rules\NifValidator#validate');
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
My Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Authentication\Register;
use App\Http\Controllers\Controller;
use Exception;
class RegisterController extends Controller
{
use \App\Traits\Helpers\ResponseJSON;
public function create()
{
try {
$payload = request()->all();
$rules = [
'nif' => 'required',
'name' => 'required',
'email' => 'required|email',
'password' => [
'required',
'string',
'min:8', // must be at least 8 characters in length
'regex:/[A-Za-z]/', // must contain at least one uppercase letter
'regex:/[0-9]/', // must contain at least one digit
],
'country' => 'required',
];
$messages = [
'password.regex' => 'A password precisa ter no minimo 1 letra e 1 número',
];
//portugal
if (176 == $payload['country']) {
// if (!Cliente::validaNif($payload['nif'])) {
// throw new Exception("register.nif_invalid");
// }
$rules['nif'] = "nifvalidator";
}
$this->validate(request(), $rules, $messages);
return $this->responseJSON([], 'register.register_success');
} catch (\Illuminate\Validation\ValidationException $validExcept) {
return $this->responseJSON([], $validExcept->getMessage(), 401);
} catch (Exception $except) {
return $this->responseJSON([], $except->getMessage(), 401);
}
}
}
The second problem is that if I noticed the controller I did a regex validation in the password field to identify if there is a letter or a number, I also customized the message that would appear in the regex field, but the message that returns is always the same "The given data was invalid.
To be honest, I don't know what to do anymore, everything I found on the internet I tried and it didn't work.
I really appreciate the help.
If I am correct the error is due to not using passes() passes is a function predefined in interface Rule which you have implemented,
So, I guess it should work by changing in the service provider,
public function boot(): void
{
\Validator::extend('empty_if', function($attribute, $value, $parameters, $validator) {
$rule = new \App\Rules\NifValidator();
return $rule->passes();
});
// or you can try though I have not sure of the commented method if it works you can inform me It would be new knowledge for me.
// \Validator::extend('nifvalidator', '\App\Rules\NifValidator#passes');
}
If it doesn't work you can always add it in the $messages(though it is not what you have asked but just as second option)
$messages = [
'password.regex' => 'A password precisa ter no minimo 1 letra e 1 número',
'nif.nifvalidator' => ':attribute inválido'
];