Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMayur Pande
Courses Plus Student 11,711 PointsUndefined index error
I am using slim-3 to build an authentication system. However at the moment I am struggling to get the errors to display on the sign-up page;
It keeps giving me the error
Undefined index: errors in /var/www/html/tobylindsell.com/app/Middleware/ValidationErrorsMiddleware.php on line 23, referer: http://tobylindsell.com/admin
However when I run a var_dump($_SESSION['errors']
on my Validator
file it shows all the errors. Only when passed to my ValidationErrorsMiddleware.php
file it doesn't show up.
Originally I was getting the error;
Undefined: _SESSION variable
But then I put a session_start
at the top of my ValidationErrorsMiddleware.php
this got rid of this error but not the
Undefined index: errors
Here is my ValidationErrorsMiddlesware.php
<?php
namespace App\Middleware;
use App\Validation\Validator;
session_start();
//inherits base middleware
class ValidationErrorsMiddleware extends Middleware{
public function __invoke($request,$response,$next){
$this->container->view->getEnvironment()->addGlobal('errors',$_SESSION['errors']);
//we unset the session as we no longer need it
unset($_SESSION['errors']);
//after state has changed
$response = $next($request,$response);
return $response;
}
}
Here is my Validator.php
<?php
namespace App\Validation;
use Respect\Validation\Validator as Respect;
//used for error checking see try catch block below
use Respect\Validation\Exceptions\NestedValidationException;
if(!isset($_SESSION)){
session_start();
}
class Validator{
protected $errors;
//create validate method
public function validate($request, array $rules){
foreach($rules as $field => $rule){
try{
//helps pulling back error messages
$rule->setName(ucfirst($field))->assert($request->getParam($field));
}catch(NestedValidationException $e){
//append to error list see property. we pass in field var here to keep track
//getMessages because there could be more than one assertion fail
$this->errors[$field] = $e->getMessages();
}
}
$_SESSION['errors'] = $this->errors;
return $this;
}
public function failed(){
//return/check if the errors are not empty
return !empty($this->errors);
}
}