Welcome Guest, Not a member yet? Register   Sign In
Redirection inside controller
#1

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.
Reply
#2

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.
Reply
#3

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.
Reply
#4

(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.
Reply
#5

(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. )))
Reply
#6

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');
}
Reply
#7

@ Gurutechnolabs

There is nothing wrong with his code so your point is pointless.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#8

(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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB