0

Let's say we want to redirect a user to a form page with some errors after submitting. I have this method in my controller.

return redirect('create')->withErrors($errors)->withInputs($inputs);

Now I have a helper function named redirect which returns a new Redirect object.

function redirect($fileName)
{
 return new Redirect($fileName);
}

and here is the sturcture of Redirect class

class Redirect
{

  public function __construct($fileName)
  {
    header("Location: " . $fileName);

    return $this;
  }


  public function withErros($errors)
  {
    session_start();
    $_SESSION['errors'] = $errors;

    return $this;
  }



  public function withInputs($inputs)
  {
    session_start();
    $_SESSION('inputs') = $inputs;

    return $this;
  }
}

The first chaining method (withErrors) runs correctly and I can show errors in my view. But the second one (withInputs) never runs. I think it's because of header function in PHP. Can somebody help me, please?

6
  • Then it's $_SESSION['inputs'] Commented Nov 8, 2016 at 20:12
  • withErros should be withErrors. Commented Nov 8, 2016 at 20:13
  • No, it was just a typo when I typed it here. Commented Nov 8, 2016 at 20:14
  • Check your error log for Headers already sent warning. Commented Nov 8, 2016 at 20:14
  • You are redirecting within __construct, so the behavior of PHP will be unkown. And returnnig $this is not needed in a constructor. Commented Nov 8, 2016 at 20:16

1 Answer 1

1
class Redirect
{
  protected $filename;
  public function __construct($fileName)
  {
      session_start();
      $this->filename=$filename;
  }
  public function __destruct()
  {
      $this->redirect();
  }
  public function withErros($errors)
  {
      $_SESSION['errors'] = $errors;
      return $this;
  }
  public function withInputs($inputs)
  {
      $_SESSION('inputs') = $inputs;
      return $this;
  }
  public function redirect(){
      header("Location: " . $this->filename);
      exit;
  }
}

This can be a solution.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.