Welcome Guest, Not a member yet? Register   Sign In
Redirect to a different page from Library class in CI4
#1

I would like to make a redirect from Library class in CI4. It does not work. I am changing the code from CI3 to CI4 and after I read a lot of topics regarding redirect I could not find an example for my case.
In CI3 it was easy to use redirect():
PHP Code:
redirect(base_url($redirect_url), 'location'301); 
I used these redirects and it does not work:
PHP Code:
return redirect()->to(base_url($redirect_url));
return 
redirect()->to($redirect_url); 

I am getting an error if I use redirect()->route():
The route for URL cannot be found.
PHP Code:
return redirect()->route($redirect_url,[], 301); 


This is not from Controller. I need a redirect to a different page from Library Class, which is located in APP\Libraries\LibraryFolder\LibraryClass.php

Please let me know if there is a way to make it work.
Reply
#2

This works in a html view may work in a library not sure or tested.
PHP Code:
// Try to use a named route.                        |name
$routes->get('{locale}/blog''Blog::index', ['as' => 'blog']);

// then try the redirect
return redirect()->to('blog'); 
What did you Try? What did you Get? What did you Expect?

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

(01-29-2025, 11:50 PM)InsiteFX Wrote: This works in a html view may work in a library not sure or tested.
PHP Code:
// Try to use a named route.                        |name
$routes->get('{locale}/blog''Blog::index', ['as' => 'blog']);

// then try the redirect
return redirect()->to('blog'); 

No, this redirect does not work from the Library class.
I tried to use header() and it works only with exit()

PHP Code:
header('Location: 'base_url($redirect_url));
exit(); 

I created, as a temporary solution, a function in helper:

PHP Code:
function redirect_to_page($page) {
    header('Location: '$page);
    exit();


I am using it in the library class:

PHP Code:
redirect_to_page(base_url($redirect_url)); 

It would be better to use CodeIgniter methods, but so far I could not find a solution.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB