(CI 4) How to redirect within Controller? - codeigniter

how can I refer to another within one controller? In CI3 (for example in the controller client.php) I solved this as follows:
redirect('/Clients', 'refresh');
but that no longer seems to work in CI4. (Msg: "route cannot be found while reverse-routing.")
I Also tried
redirect()->route('/Clients');
but the error is the same.
redirect()->to('/Clients');
redirects nowhere (no output, nothing)
For a better understanding: I want to use a controller (e.g. Clients/create to Clients/details)

What you should notice is that redirect() does not just set headers like it used to do in CI3. In CI4 it returns a RedirectResponse object with which you can ask your controller to do a redirection.
To do so, you need to return this RedirectResponse object inside your controller. Without the return statement, the redirection won't happen.
An other thing to notice is that redirect() can be called with some "options" :
Going to a named route
return redirect()->route('named_route');
or
return redirect('named_route');
To use this, you need to add a named routes in your app/Config/Routes.php file :
$routes->get('/', 'MyController::index', ['as' => 'named_route']);
Going to a specific URI
return redirect()->to('Clients');
It will redirect you to your base url with /Clients at the end.
Please check out the doc for further informations : https://codeigniter.com/user_guide/general/common_functions.html#redirect

#ViLar gives the correct answer, but it's important to note that when using auto routing the CI3 version redirect('home'); becomes return redirect()->to('home');
It's confusing to just say "Going to a specific URI" and omit that this means auto routed controllers.

Related

Set tab name in redirect to route in laravel

in laravel 8 i will redirect the user to a route after doing the query.
There are many tabs on the page where I want the user to be transferred
I wrote the code like this
(Of course I know it's wrong, but I wanted to try, and yet I did not think of another way
return redirect()->route('admin.auth.user.show', $user . "#edit-information")->withFlashSuccess(__('The user was successfully updated.'));
I get an error with this code
What is your solution?
What you can do to activate for example bootstrap tab based on #web paramater is use the redirect() method like this:
return redirect()->route('backend.settings.show', ['eshop' => $eshop->id, '#homeImages']);
Eshop is regular route parameter but '#homeImages' is added to the end of the route which is then picked up by the js on page load.
In Laravel there is a withFragment method, which add a fragment identifier to the URL.
return redirect()->route('admin.auth.user.show', ['user' => $user])->withFragment('edit-information');
https://laravel.com/api/8.x/Illuminate/Http/RedirectResponse.html#method_withFragment

Whats the difference between redirect and this in Codeigniter?

I am new in Codeigniter and it's one of the good frameworks of php. But on some conditions I'm confused. Like this one. If any of you have any clarification about my dough, it's a great help for me.
Offcouse redirects refresh the page and $this not but apart from this I want to know - anyhow both of them used to go to somewhere else on view pages or like in other controller or in same controller to other methods.
But we don't use these side by side because when getting any of them it will go to that page or method without checking the next lines.
In case of a normal difference then have lot's of but I just want to know about the condition of going to next page or method when we use redirect or $this like this -
$this->Function($value); //It's method of same controller.
redirect('Controller/function'); //It's also doing same with page reload.
Thank for looking my problem.
Redirect()
When you will call any function of helper in codeigniter then you can call function directly without using any object. Helper in Codeigniter is collection of functions.
Redirect() method is a part of URL helper in Codeigniter.
For your ref. https://www.codeigniter.com/user_guide/helpers/url_helper.html
So, just load helper using $this->load->helper('url'); or you can also mention in autoload.php file.
$this->Function(); used to call a function from same controller
$this->Function(); used to call a function from same controller
redirect()
While building a web application, we often need to redirect the user from one page to another page. CodeIgniter makes this job easy for us. The redirect() function is used for this purpose.
redirect($uri = '', $method = 'auto', $code = NULL)
The first argument can have two types of URI. We can pass full site URL or URI segments to the controller you want to direct.
The second optional parameter can have any of the three values from auto, location or refresh. The default is auto.
The third optional parameter is only available with location redirects and it allows you to send specific HTTP response code.
Redirect means jumping to another function mentioned in the redirect method.
$this->Function($value); => jumping to another function and you can execute the code of the same function as well as pass the value back by returning value.
When you send request to codeigniter generally CI controller gets called and then function which is mentioned in uri segment. like below... So this will be another request.
redirect('Controller/function'); //It's also doing same with page reload.
But when you have to call another function within the same request then you can use below approach
$this->Function($value); //It's method of same controller.
This will execute the given function and return the value within same request.

Laravel 5.7 Passing a value to a route in a controller

My controller posts a form to create a new page. After posting the form I need to redirect the user to the new page that will have the contents for that page that were entered in the previous form. If I simply do return view('mynewpageview', compact('mycontent')); where my mycontent is the object used to execute the $mycontent->save(); command, I carry the risk for someone refreshing the url thus posting the same content twice by creating a new page.
Instead I would like to redirect the user to the actual page url.
My route is
Route::get('/newpage/{id}', 'PageController#pagebyid'); and if I use return redirect()->route('/newpage/$pageid'); where $pageid = $mycontent->id; I get Route not defined error.
What would be the solution either to stop someone from resubmitting the content or a correct syntax for passing the parameter?
The correct answer that works for me is -
Give your route a name in the routes file
Then pass the parameters with an array as shown below in the controller.
return redirect()->route('newpageid', ['id' => $pageid]);
With basic (unnamed) routes, the correct syntax was return redirect('/newpage/'.$pageid);
You have already found out you can alternatively use named routes.
Last but not least, thanks for having considered the "double submit" issue! You have actually implemented the PRG pattern :)

Codeigniter - custom routes

Lets say I have a controller 'standard' with an action 'main'.
If I go to www.myapp.com/standard/main it will invoke the main action in the standard controller.
Now if I want to change the URL I go into the routes.php and set sth like the following:
$route['welcome'] = "standard/main";
Now I can visit www.myapp.com/welcome and it will invoke the same action.
However it is still possible to visit www.myapp.com/standard/main. I now have two routes which lead to the same controller action.
Is this the usual way or should I somehow disable the now unwanted www.myapp.com/standard/main route? If so, how would I do that?
Thanks in advance.
That is completely for you to decide the default behavior. If you decide to disable the original url, you can write something like
$route['standard/main'] = 'standard/404';
Or any custom location, it depends on your project and how you wish it should look like, for example you can 'block' any method from being accessed directly:
$route['standard/(:any)'] = 'standard/404';
But bear in mind, if you route like you did $route['welcome'] = "standard/main";, then you should always remember that the function $this->uri->segment(n) will show different values, for example if I will go to url yoursite.com/welcome/123, the value of $this->uri->segment(2) will be 123, but if I visit the original URL yoursite.com/standard/main/123, it's value will change to main.
Bear that in mind and decide for yourself!
Assuming that this is a common structure you'll be using, for each action, you can check the segment's in the URL and then redirect appropriately. In the case of going from standard/main to welcome, you would have the following:
class Standard extends CI_Controller {
public function main() {
if($this->uri->segment(1) == 'standard') {
redirect('welcome', 'location', '301');
}
}
}
This would then check the first segment in the URL and if it sees that you've come to this URL, redirect you to the appropriate route. This can then be applied to each action you want to do the same thing for. Supplying a 301 signifies a permanent redirect.
Update
Just found a similar (the same?) question: Only allow URL's specified in routes to be seen in Codeigniter

How can I prevent duplicate content when re-routing pages in CodeIgniter?

Say I have a controller, "Articles" but I want it to appear as a sub-folder (e.g. "blog/articles"), I can add a route like this:
$route['blog/articles'] = 'articles';
$route['blog/articles/(:any)'] = 'articles/$1';
This works fine, the only problem now is that example.com/articles and example.com/blog/articles both use the Articles controller and thus resolve to the same content. Is there a way to prevent this?
To add a little more clarity in case people aren't understanding:
In this example, I don't have a 'blog' controller, but I want 'articles' etc to appear to be in that subfolder (it's an organization thing).
I could have a blog controller with an 'articles' function, but I'm likely to have a bunch of 'subcontrollers' and want to separate the functionality (otherwise I could end up with 30+ functions for separate entities in the blog controller).
I want example.com/articles to return a 404 since that is not the correct URL, example.com/blog/articles is.
Shove this in your controller:
function __construct()
{
parent::Controller();
$this->uri->uri_segment(1) == 'blog' OR show_404();
}
You can use subfolders in Codeigniter controllers, so in CI, the following directory structure works:
application/controllers/blog/articles.php and is then accessed at
http://example.com/blog/articles/*.
If, for some reason, you're set on routing instead of accessing the controllers in folders (you want to have a blog controller, for example, and don't want to route to it), you can do as suggested above and add the test for 'blog' to the constructor.
If you're in PHP5, you can use the constructor function like this:
function __construct()
{
parent::Controller();
$this->uri->uri_segment(1) == 'blog' OR redirect('/blog/articles');
}
or, in PHP4, like this:
function Articles()
{
parent::Controller();
$this->uri->uri_segment(1) == 'blog' OR redirect('/blog/articles');
}
I would suggest using redirect('blog/articles') instead of show_404(), though, so that you're directing users who hit /articles to the correct location, instead of just showing them a 404 page.
Routing there does not mean it will use a different controller, it just creates alias url segment to same controller. The way will be to create another controller if you are looking to use a different controller for those url segments.
If both /blog/ and /articles/ use the same controller, you can reroute one of them to a different one by just adding a new rule in your routes file.

Resources