CodeIgniter Forums
Redirection inside controller - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: Redirection inside controller (/showthread.php?tid=71854)



Redirection inside controller - yuryn1961 - 10-01-2018

Hi there,

A short fragment of my code in controller:

Code:
public function index($jack) {
   if($jack === 'John') {
       $this->error404();
       return null;
   }
   $this->load->view('mypost');
}

public function error404() {
   $this->load->view('error');
}

My question: is it correct to use return in a controller function? Otherwise, the view 'mypost' will be loaded in any case.

Thank you.


RE: Redirection inside controller - Pertti - 10-01-2018

Hey,

Absolutely.

Haven't tried 4.0 yet, so that system might work differently, but 3.x you echo output or load views yourself, and can return out of controller method at any point when controller code is finished, but you want to let CI finish properly, instead of abruptly calling exit or die.


RE: Redirection inside controller - dave friend - 10-02-2018

I'd like to add that you do not need to return a value. So instead of
PHP Code:
return null
a simple
PHP Code:
return; 
will do.


RE: Redirection inside controller - yuryn1961 - 10-02-2018

(10-01-2018, 11:11 PM)Pertti Wrote: Hey,

Absolutely.

Haven't tried 4.0 yet, so that system might work differently, but 3.x you echo output or load views yourself, and can return out of controller method at any point when controller code is finished, but you want to let CI finish properly, instead of abruptly calling exit or die.

Thank you, Pertti.


RE: Redirection inside controller - yuryn1961 - 10-02-2018

(10-02-2018, 09:19 AM)dave friend Wrote: I'd like to add that you do not need to return a value. So instead of
PHP Code:
return null
a simple
PHP Code:
return; 
will do.

Thank you, dave friend. Actually, I have tried both. They work. So 'null' is here without any special reason. )))


RE: Redirection inside controller - Gurutechnolabs - 11-06-2018

You must need to put if and else condition for example

public function index
($jack) {
if($jack === 'John') {
$this->error404();
}else{
$this->load->view('mypost');
}
}

OR

public function index
($jack) {
if($jack === 'John') {
$this->error404();
exit;
}
$this->load->view('mypost');
}


RE: Redirection inside controller - InsiteFX - 11-06-2018

@ Gurutechnolabs

There is nothing wrong with his code so your point is pointless.


RE: Redirection inside controller - dave friend - 11-22-2018

(11-21-2018, 11:24 PM)Jennytrump Wrote: You should include the base_url() or site_url() (depends on your config) to redirect() function:

redirect(base_url('your_controller/your_method'));

That is not necessary. The redirect function does this automatically as part of its friendly service.