Search code examples
phpcodeigniter-4

Codeigniter 4 Couldn't access a page, overridden by routes


So I have a method in the Buku controller that shows details of books with the url

example.com/buku/detail/slug

I wanted to change so that you can find books using slug with shown below

example.com/buku/slug

I have added the routes with following code

$routes->get('/buku/(:segment)', 'Buku::/detail/$1')

It works flawlessly. After that I added a button that goes to method 'tambah'

example.com/buku/tambah

But everytime the button is clicked, it somehow shows error that you can't go to url above because of there's no 'tambah' slug in /detail/

I think the problem is within the route that I added. Do I miss something crucial?

This is detail method

public function detail($slug)
    {
        $data = [
            'title' => 'Detail Buku',
            'buku' => $this->bukuModel->getBuku($slug)
        ];

        return view('buku/detail', $data);
    }

And this is Buku model

class BukuModel extends Model
{
    protected $table = 'buku';
    protected $useTimestamps = true;

    public function getBuku($slug = false)
    {
        if ($slug == false) {
            return $this->findAll();
        }

        return $this->where(['slug' => $slug])->first();
    }
}

Edit: Added some more code for information


Solution

  • During my work, I noticed that the CI4 is slightly different from previous experiences with CI3, but at the same time CI4 gives additional possibilities for managing application routes.

    In the example you have presented, there is no difference between the parameter name for the detail method and the method name tambah. Therefore, the CI4-based application does not know which route is correct. As I mentioned, CI4 comes out with some solutions to your problems.

    1. CI4 - URI Routing - Mapping multiple routes - In your case, the map() method will be more convenient. It is worth emphasizing that cascading can have an impact on proper operation in line with your expectations.
    2. CI4 - Controllers - Remapping Method Calls - The _remap() method used in the controller allows you to ignore the default method call, allowing you to.

    Unfortunately, I can't see the code for tambah, so I don't know if it will have any parameters. Your _remap() code might look like this:

    public function _remap($method,...$params)
    {
        switch ($method) {
            case 'tambah':
                return $this->$method(...$params);
                break;
            default:
                return return $this->detail(...$params);
                break;
        }
    }