Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use withErrors with Exception error messages in Laravel4?

Assume that I have this Exception Message

catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
{
     echo 'Login field is required.';
}

How can I pass this message Login field is required using withErrors()?

return Redirect::to('admin/users/create')->withInput()->withErrors();
like image 285
Roseann Solano Avatar asked Aug 21 '13 21:08

Roseann Solano


2 Answers

return Redirect::to('admin/users/create')
       ->withInput()
       ->withErrors(array('message' => 'Login field is required.'));
like image 56
giannis christofakis Avatar answered Sep 28 '22 05:09

giannis christofakis


This depends on where you are catching the exception.

Sentry does not use the Validator class. So if you want to return an error message the Laravel way, you should create a separate Validator object and validate first, then only pass to Sentry after your validation has passed.

Sentry will only be able to pass 1 error back as it is catching a specific exception. Furthermore, the error will not be of the same type as the error in the validation class.

Also, if Sentry does catch the exception, then your Validation is clearly not working.

Code below is not how you should do it, but more to show a combination of what I believe shows ways of working with Laravel / Sentry

Example User model

class User extends Eloquent {
  public $errors;
  public $message;

    public function registerUser($input) {

       $validator = new Validator::make($input, $rules);
       if $validtor->fails() {
          $this->errors = $validator->messages();
          return false;
       }

        try {
            // Register user with sentry
            return true;
        }
        catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
        {
            $this->message = "failed validation";

            return false;
        }
       }
    }
}

UserController

class UserController extends BaseController {

public function __construct (User $user) { $this->user = $user; }

public function postRegister()
{
    $input = [
        'email' => Input::get('email'),
        'password' => Input::get('password'),
        'password_confirmation' => Input::get('password_confirmation')
    ];

    if ($this->user->registerUser($input)) {
        Session::flash('success', 'You have successfully registered. Please check email for activation code.');
        return Redirect::to('/');
    }
    else {
        Session::flash('error', $this->user->message);
        return Redirect::to('login/register')->withErrors($this->user->errors)->withInput();
    }
}   
like image 45
Gravy Avatar answered Sep 28 '22 05:09

Gravy