Search code examples
phpcodeignitervalidationcodeigniter-4

Validation errors not sent using redirect withInput()


I'm trying to send my validation errors to another method by using redirect

public function save()
    {

        //validasi input
        if (!$this->validate([
            'judul' => 'required|is_unique[komik.judul]'
        ])) {
            return redirect()->to('/komik/create')->withInput();
        }

this is the create() method

public function create()
    {
        session();
        $data = [
            'title' => 'Form Tambah Data Komik',
            'validation' => \Config\Services::validation()

        ];

        return view('komik/create', $data);
    }

This is a snippet of my create.php view form where I'm trying to validate

<form action="/komik/save" method="post" enctype="multipart/form-data">

                <?php d($validation) ?>
                <?= $validation->listErrors();; ?>

this is the form enter image description here

The problem is that the validation errors in save() is not sent to the create() method. But the validation errors exist in the save() method which I can prove by adding $validation = \Config\Services::validation(); dd($validation); in save(). This is what happens when I click "Tambah Data" button after I add the code enter image description here

as you can see there is a validation error, it's just not sent to the create() method enter image description here

I tried using return view(), this works but it creates another problem. I would like to use return redirect() instead.

This is my routes

$routes->get('/', 'Pages::index');
$routes->get('/komik/create', 'Komik::create');
$routes->get('/komik/edit/(:segment)', 'Komik::edit/$1');
$routes->post('/komik/save', 'Komik::save');
$routes->delete('/komik/(:num)', 'Komik::delete/$1');
$routes->get('/komik/(:any)', 'Komik::detail/$1');

What can I do to solve this problem? Thanks


Solution

  • I found the solution, apparently there's a bug with redirect()->withInput() in CI. You need to use validation_errors(), validation_list_errors() and validation_show_error() to display validation error. Also you don't need to write $validation = \Config\Services::validation();. Read https://codeigniter4.github.io/CodeIgniter4/installation/upgrade_430.html#redirect-withinput-and-validation-errors