From the controller, you would normally do...
return redirect(route('myPlace'))->withErrors($errorBag);
// or
Return view('myView')->withErrors($errorBag);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
my comment store file code
<?php
$db = new Database();
$user_id = $_POST['user_id'];
$post_id = $_POST['post_id'];
$comment = $_POST['comment'];
// validating the comment
$errors = [];
if (strlen(trim($comment)) == 0) {
$errors['comment'] = "Comment is required.";
} else if (strlen(trim($comment)) > 1000) {
$errors['comment'] = "The maximum length of a comment should be 1000 characters.";
}
// storing the comment into the comments table
if(empty($errors))
{
$comment = $db->query(
"INSERT INTO comments (post_id, user_id, comment)
VALUES (:post_id, :user_id, :comment)",
[
'post_id' => $post_id, 'user_id' => $user_id, 'comment' => $comment
]
);
if ($comment) {
$_SESSION['msg'] = "Commented successfully!";
header("location: /posts/post?post={$post_id}");
}
}else{
// how to pass the error to that form
// Redirect back to the form page
header("location: /posts/post?post={$post_id}");
}
my routes file url route
$router->get('/posts/post', "core/Http/controllers/posts/show.php");
my Router file code
<?php
require base_path("core/middleware/Middleware.php");
class Router
{
protected $routes = [];
public function add($uri, $controller, $method)
{
$this->routes[] = [
'uri' => $uri,
'controller' => $controller,
'method' => $method,
'middleware' => null
];
return $this; //return object of the $routes
}
public function get($uri, $controller)
{
return $this->add($uri, $controller, "GET");
}
public function post($uri, $controller)
{
return $this->add($uri, $controller, "POST");
}
public function put($uri, $controller)
{
return $this->add($uri, $controller, "PUT");
}
public function patch($uri, $controller)
{
return $this->add($uri, $controller, "PATCH");
}
public function delete($uri, $controller)
{
return $this->add($uri, $controller, "DELETE");
}
public function route($uri, $method)
{
foreach ($this->routes as $route) {
if ($route['uri'] == $uri && $route['method'] == strtoupper($method)) {
// middleware instance will auto load
if ($route['middleware']) {
$middleware = Middleware::MAP[$route['middleware']];
// var_dump($middleware);
$middleware = new $middleware();
$middleware->handle();
}
return require base_path($route['controller']);
}
}
// abort if uri not found
$this->abort(404);
}
public function only($key)
{
$this->routes[array_key_last($this->routes)]['middleware'] = $key;
// return $this;
}
protected function abort($code = 404)
{
// http_response_code($code);
views("status-error/{$code}.php");
die();
}
}
Please or to participate in this conversation.