Can be textarea field sent by email in Laravel 8? - php

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);
}
}

Related

Symfony 6.2 witch docker php-fpm

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 ?

Making laravel system 7 based on laravel 5.3 system but can't log in

When I press login after setting email and password it only blinks and nothing else happens. I have a A Larvel Passport system with Oauth2 login.
This is a working system but in V. 5.3: https://test.webshooter.se In the Laravel 7 system I can do everything like show competitions, map, register users, reset passwords, and get emails to and from but is not able to login. I have come so far that the user is authenticated in such a way that there is both oauth_refresh_tokens and oauth_access_tokens registred in the database for every login clicked.
Here is the login blade:
<div class="row">
<div class="col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4">
<div class="panel panel-primary">
<div class="panel-heading">
{{_('Logga in')}}
</div>
<div class="panel-body">
<div ng-class="{'hide': loggingIn}">
<div class="form-group">
<input type="text" name="email" ng-model="auth.email" id="email" class="form-control" placeholder="{{_('E-postadress')}}" ng-enter="login();" autofocus>
</div>
<div class="form-group">
<input type="password" name="password" ng-model="auth.password" class="form-control" placeholder="{{_('Lösenord')}}" ng-enter="login();">
</div>
<a class="btn btn-success btn-block" ng-click="login();" ng-class="{'disabled': loggingIn}">{{_('LOGIN')}}</a>
<div class="row margin-top-20">
<div class="col-sm-12 text-center">
<a ui-sref="auth.password">{{_('Glömt ditt lösenord?')}}</a>
</div>
</div>
<div class="row margin-top-20">
<div class="col-sm-12 text-center">
<a ui-sref="auth.register">{{_('Inget konto? Registrera dig')}} »</a>
</div>
</div>
</div>
<div class="hide text-center text-muted" ng-class="{show: loggingIn}">
<i class="fa fa-2x fa-spinner fa-spin"></i>
<p>{{_('LOGGING IN')}}</p>
</div>
</div>
</div>
</div>
</div>
<script>$('#email').focus();</script>
This is part of the AuthenticateController:
<?php
namespace App\Http\Controllers\Api;
use App\Jobs\SendActivationEmail;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserInvite;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Http\Requests;
use Illuminate\Http\Request;
class AuthenticateController extends Controller
{
/**
* #param Request $request
*
* #return \Illuminate\Http\JsonResponse
*/
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
try {
// verify the credentials and create a token for the user
if (! $token = \JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials', 'message' => _('Vänligen kontrollera ditt användarnamn och/eller lösenord.')], 401);
} elseif (JWTAuth::toUser($token)->activation_code && JWTAuth::toUser($token)->created_at < date('Y-m-d H:i:s', strtotime('-2 weeks'))) {
return response()->json(['error' => 'user_inactive', 'message' => _('Din e-postadress har inte aktiverats ännu. Du bör ha ett e-postmeddelande innehållande en aktiveringslänk.')], 401);
} elseif (JWTAuth::toUser($token)->deleted_at) {
return response()->json(['error' => 'user_deleted', 'message' => _('Ditt konto har inaktiverats. Ta kontakt med vår kundsupport om du vill återaktivera ditt konto.')], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token', 'message' => _('Någonting verkar ha gått ha fel. Prova gärna igen.')], 500);
}
$user = \Auth::user();
// if no errors are encountered we can return a JWT
return response()->json(compact('token','user'));
}
public function updatePassword(Requests\PasswordRequest $request)
{
$user = \Auth::user();
if(\Hash::check($request->get('password'), $user->password)):
return response()->json(['message'=>_('Nuvarande lösenord verkar inte stämma.')], 401);
else:
$user->update(['password'=>bcrypt($request->get('password'))]);
return response()->json(['message'=>_('Ditt lösenord har ändrats')]);
endif;
}
/**
* #return \Illuminate\Http\JsonResponse
*/
public function getAuthenticatedUser(){
$user = \Auth::user();
$user->makeVisible([
'email',
'no_shooting_card_number',
'shooting_card_number',
'birthday',
'phone',
'mobile',
'gender',
'grade_trackshooting',
'grade_field'
]);
// the token is valid and we have found the user via the sub claim
return response()->json(compact('user'));
}
public function updateAuthenticatedUser(\App\Http\Requests\UserRequest $request){
try {
$user = \Auth::user();
$data = $request->all();
if($request->has('set_no_shooting_card_number')) $data['no_shooting_card_number'] = date('Y-m-d H:i:s');
if($request->has('shooting_card_number')) $data['no_shooting_card_number'] = null;
$user->update($data);
$user->makeVisible([
'email',
'no_shooting_card_number',
'shooting_card_number',
'birthday',
'phone',
'mobile',
'gender',
'grade_trackshooting',
'grade_field'
]);
return response()->json(compact('user'));
} catch (JWTException $e) {
if ($e instanceof TokenExpiredException) {
return response()->json(['token_expired'], $e->getStatusCode());
} else if ($e instanceof TokenBlacklistedException) {
return response()->json(['token_blacklisted'], $e->getStatusCode());
} else if ($e instanceof TokenInvalidException) {
return response()->json(['token_invalid'], $e->getStatusCode());
} else if ($e instanceof PayloadException) {
return response()->json(['token_expired'], $e->getStatusCode());
} else if ($e instanceof JWTException) {
return response()->json(['token_invalid'], $e->getStatusCode());
}
}
}
/**
* #param Request $request
*
* #return static
*/
public function register(\App\Http\Requests\RegistrationRequest $request){
try {
//Verify recaptcha request.
$verifyUrl = 'https://www.google.com/recaptcha/api/siteverify';
$verifyUrl .= '?hl=sv_SE';
$verifyUrl .= '&secret='.env('RECAPTCHA_SECRET_KEY');
$verifyUrl .= '&response='.$request->get('recaptcharesponse');
$recaptchaResponse = json_decode(file_get_contents($verifyUrl), true);
if(!isset($recaptchaResponse['success']) || $recaptchaResponse['success'] !== true):
return response()->json(['error' => 'recaptcha_error', 'message' => _('Någonting gick fel, vänligen försök igen.')], 500);
endif;
$data = $request->all();
$data['activation_code'] = md5($data['email'].time());
$data['password'] = bcrypt($request->get('password'));
$data['language'] = \App\Models\Languages::defaultLanguage();
$user = User::create($data);
/**
* Get userinvite based on email address and update the invite with a timestamp.
* If the request has an invite_token check if the token is present as an id.
*/
$inviteQuery = Userinvite::where('email', $request->get('email'));
/* if($request->has('invite_token')):
$optimus = new \Jenssegers\Optimus\Optimus(env('OPTIMUS_PRIME'), env('OPTIMUS_INVERSE'), env('OPTIMUS_RANDOM'));
$inviteId = $optimus->decode($request->get('invite_token'));
$inviteQuery->orWhere('id', $inviteId);
endif;*/
if($invite = $inviteQuery->first()):
$invite->update(['registered_at'=>$user->created_at]);
endif;
/**
* Send activation e-mail works 2021-12-16
*/
if(env('APP_ENV') == 'local'):
$this->dispatch(new SendActivationEmail($user));
endif;
return response()->json('success');
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'Fel vid registrering', 'message' => _('Någonting gick fel, vänligen försök igen.')], 500);
}
}
public function cancelAccount()
{
$user = \Auth::user();
First part of the routes (routes/api.php):
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the \\ RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('/auth/register', ['as'=>'auth.register', 'uses'=>'Controllers/AuthenticateController#register']);
Route::group(['prefix'=>'v'.env('API_VERSION')], function(){
Route::post('activate', 'AuthenticateController#activate');
Route::post('register', 'AuthenticateController#register');
#Route::post('refresh', 'AuthenticateController#refresh');
Route::post('password/email', 'PasswordController#postEmail');
Route::post('password/reset', 'PasswordController#postReset');
Route::group(['prefix'=>'public'], function(){
Route::resource('competitions', 'PublicCompetitionsController', ['only' => ['index', 'show']]);
});
Route::group(['middleware'=>['auth:api', 'checkUserActive']], function(){
Route::get('authenticate/user', 'AuthenticateController#getAuthenticatedUser');
Route::put('authenticate/user', 'AuthenticateController#updateAuthenticatedUser');
Route::put('authenticate/updatePassword', 'AuthenticateController#updatePassword');
Route::post('authenticate/cancelAccount', 'AuthenticateController#cancelAccount');
Route::get('users/invite', 'AuthenticateController#getInvite');
Route::post('users/invite', 'AuthenticateController#sendInvite');
Route::put('clubs', ['as'=>'clubs.update', 'uses'=>'ClubsController#update']);
Route::get('clubs/getUserClub', ['as'=>'clubs.getUserClub', 'uses'=>'ClubsController#getUserClub']);
Route::post('clubs/addNewClub', ['as'=>'clubs.addNewClub', 'uses'=>'ClubsController#addNewClub']);
Getting this error when trying to login:
[2021-12-30 13:59:38] local.ERROR: count(): Parameter must be an array or an object that implements Countable {"userId":11,"exception":"[object] (ErrorException(code: 0): count(): Parameter must be an array or an object that implements Countable at /Users/ralph/onsdagWS7/webshooter_web_upgrade/app/Models/User.php:96)
[stacktrace]
And in the user.php:
public function getClubsIdAttribute()
{
if(!$this->relationLoaded('Clubs')):
$this->load('Clubs');
endif;
(96) return (count($this->Clubs->first())) ? $this->Clubs->first()->id : null;
}
What could be the problem? But I don't get into the dashboard blade when clicking "Login" but it returns directly back to the login page.
This is not an issue anymore. I have successfully upgraded the system to Laravel 9.17.0 present version.

Custom Validator Rules in Laravel Return always message

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'
];

Symfony3: How to change roles when I login

I want to change roles when I login, so I have a form inside my controller to log me in and a provider for my user class, but I am really lost. I've been looking several tutoriel on symfony website but I still don't have a clue how to do it. So before I login, I am authenticated as anon on the symfony toolbar. But when I login, I am not authenticated, but I see my username on the toolbar. Can you tell me what tutoriel do I need to see? I just could not see clearly how to authenticated, and I've been searching for hours...
Here is my form inside my controller :
public function indexAction(Request $request)
{
$player = new Player;
$form = $this->createFormBuilder($player)
->add('email', TextType::class, array('label' => 'Email :'))
->add('password', PasswordType::class, array('label' => 'Mot de passe :'))
->add('login', SubmitType::class, array('label' => 'Login'))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$password = $form['password']->getData();
$email = $form['email']->getData();
$encoded_pass = sha1($form['password']->getData());
$date = date_create();
/*
Recherche dans la base de données si les différents éléments entrés
sont présents afin de connecter la personne
*/
$player = $this->getDoctrine()
->getRepository('AppBundle:Player')
->findOneByEmail($email);
$pass_check = $this->getDoctrine()
->getRepository('AppBundle:Player')
->findByPassword($encoded_pass);
if(!$player)
{
return $this->redirectToRoute('registration');
}
else
{
$pseudo = $this->getDoctrine()
->getRepository('AppBundle:Player')
->findOneByEmail($email)->getPseudo();
/* Met à jour la date de connection */
$player->setDateLog($date);
/* Entre les différents élements dans la base */
$em = $this->getDoctrine()->getManager();
$em->persist($player); // prépare l'insertion dans la BD
$em->flush(); // insère dans la BD
$token = new UsernamePasswordToken($player, $player->getPassword(), "main", $player->getRoles());
$event = new InteractiveLoginEvent(new Request(), $token);
$this->container->get("event_dispatcher")->dispatch("security.interactive_login", $event);
$this->container->get("security.token_storage")->setToken($token);
return $this->redirectToRoute('accueil', array('pseudo' => $pseudo));
}
}
return $this->render('Sko/menu.html.twig', array('form' => $form->createView()));
// En plus renvoyer la balise
}
Then I have my provider :
<?php
namespace AppBundle\Security;
use AppBundle\Entity\Player;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
class PlayerProvider implements UserProviderInterface
{
protected $doctrine;
public function __construct(\Doctrine\Bundle\DoctrineBundle\Registry $doctrine){
$this->doctrine = $doctrine;
}
public function loadUserByUsername($username)
{
// make a call to your webservice here
$player = new Player();
$player = $this->doctrine
->getRepository('AppBundle:Player')
->findOneByPseudo($username);
// pretend it returns an array on success, false if there is no user
if ($player) {
$password = $player->getPassword();
$salt = $player->getSalt();
$roles = $player->getRoles();
return $player;
}
throw new UsernameNotFoundException(
sprintf('Username "%s" does not exist.', $username)
);
}
public function refreshUser(UserInterface $user)
{
if (!$user instanceof Player) {
throw new UnsupportedUserException(
sprintf('Instances of "%s" are not supported.', get_class($user))
);
}
return $this->loadUserByUsername($user->getPseudo());
}
public function supportsClass($class)
{
return Player::class === $class;
}
}
?>
Thank for your help
EDIT : In Symfony Profiler, my roles are ['ROLE_USER'] like intended when I login

Request validation, how to show errors?

I have a form that allows the user to upload 3 files.
Here is the Controller function called :
public function registerUpdate(CardAvsRequest $request){
$id = Auth::user()->id;
$first_name = User::find($id)->student->first_name;
$last_name = User::find($id)->student->last_name;
$name = $first_name . " " . $last_name;
$message = "";
if ($request->hasFile('carte-id'))
{
$image1 = $request->file('carte-id');
if($image1->isValid())
{
if ($request->hasFile('avs'))
{
$image2 = $request->file('avs');
if($image2->isValid())
{
if ($request->hasFile('permit'))
{
$image3 = $request->file('permit');
if($image3->isValid())
{
$path = config('card.path')."/$id";
$name = "carte-id.".$image1->getClientOriginalExtension();
$image1->move($path, $name);
$path = config('card.path')."/$id";
$name = "avs.".$image2->getClientOriginalExtension();
$image2->move($path, $name);
$path = config('card.path')."/$id";
$name = "permit.".$image3->getClientOriginalExtension();
$image3->move($path, $name);
$message = "Super ! Vous avez importé tous les fichiers nécessaires.";
//ici on dit dans la DB que l'utilisateur à uploadé tous les fichiers
}
}
}
}
}
}
return redirect()->route('account', $id)->with('message', $message);
}
So the Validation rules are set in CardAvsRequest.php :
class CardAvsRequest extends Request
{
/**
* 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 [
'carte-id' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
'avs' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
'permit' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
];
}
}
I would like to know how to display errors if a file isn't validated.
Isn't it supposed to work like this ?
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Any ideas ?
This is how Laravel 5.2 documentation suggestion to validate input and return error if any. The view looking good and will display error if occurred.
public function store(Request $request)
{
$rule = 'required|file|mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000';
$validator = Validator::make($request->all(), [
'file_one' => $rule,
'file_two' => $rule,
'file_three' => $rule,
]);
if ($validator->fails()) {
return redirect('account')
->withErrors($validator)
->withInput();
}
// no errors proceed managing your files
}
Yes but in that case you have to remember that you have to put that code:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
In form file.

Categories