Home > Back-end >  CodeIgniter 4: How do you enable user defined routes?
CodeIgniter 4: How do you enable user defined routes?

Time:03-14

I'm just wondering how I can redirect to StudProfile after using the UpStudProf function. After running UpStudProf function, the URL became http://localhost/csms/public/index.php/Home/StudProfile, but it should be http://localhost/Home/StudProfile and is it possible to remove the Controllers name Home on the URL?

public function StudProfile(){

$crudModel = new Mod_Stud();
$data = [];
$data['user_data'] = $crudModel->orderBy('s_id', 'ASC')->findAll();
$data['title']      = 'SMS | STUDENT PROFILE';
$data['heading']    = 'Welcome to SMS';
$data['main_content']   = 'stud-prof';  // page name
return view('innerpages/template', $data);
}

public function UpStudProf(){
$crudModel = new Mod_Stud();
$s_id = $this->request->getPost('s_id');
$data = array(
    's_lrn'   => $this->request->getPost('s_lrn'),
    's_fname' => $this->request->getPost('s_fname'),
    's_mname' => $this->request->getPost('s_mname'),
    's_lname' => $this->request->getPost('s_lname'),
    );
$crudModel->upStud($data, $s_id);
return redirect()->to('Home/StudProfile'); //return to StudProfile
}

Routes.php

$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);

CodePudding user response:

... is it possible to remove the Controllers name Home on the URL?

Use Defined Routes Only

When no defined route is found that matches the URI, the system will attempt to match that URI against the controllers and methods as described above. You can disable this automatic matching, and restrict routes to only those defined by you, by setting the setAutoRoute() option to false:

$routes->setAutoRoute(false);

Secondly, after disabling automatic matching, declare your user-defined route: app/Config/Routes.php

$routes->get('student-profiles', 'Home::StudProfile');

Lastly: \App\Controllers\Home::UpStudProf,

redirect(string $route)

Parameters: $route (string) – The reverse-routed or named route to redirect the user to.

Instead of:

// ...
return redirect()->to('Home/StudProfile'); //return to StudProfile ❌
// ...

Use this:

// ...
return redirect()->to('/student-profiles'); ✅
// ...
  • Related