redirect from one controller to another - codeigniter

My Codeigniter route.php is set to :
$route['default_controller'] = 'welcome/view';
I am trying to redirect to a test controller from the default controller's view method using redirect('test') but I am getting a Fatal error: Uncaught TypeError: Argument 1 passed to CI_Exceptions::show_exception() must be an instance of Exception, instance of Error given .
class Welcome extends CI_Controller {
public function view()
{
redirect('test');
}
}
-
class Test extends CI_Controller {
public function index()
{
echo 'hi';
}
}
I am expecting hi as the output as I am redirecting to the test controller . I am not sure what the error actually means . Could somebody please tell me what does the error mean and what is going wrong ?

For any of the functions in CodeIgniter's URL Helper (e.g. redirect(), base_url(), etc. ) to work the configuration item $config['base_url'] must be set.
The notes with this setting in /application/config/config.php says
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| WARNING: You MUST set this value!
|
| If it is not set, then CodeIgniter will try guess the protocol and path
| your installation, but due to security concerns the hostname will be set
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
Pay particular attention to the line
WARNING: You MUST set this value!
and don't forget the trailing slash.

Try this
redirect(base_url('Test/index'));

define route for test controller also in your config/routes.php file.
$route['test']='Test/index';
And redirect this url.
redirect(base_url('test'), 'refresh');

Related

Need to replace a static value in all controllers even in whole project. Is there any way that i can change this value from only a single function?

I have a pre-build project and there is some static value passed in the whole project. Instead of looking in every controller and blade file, I want to change these static values replace to the values from the env file.
**What I tried: **
In the bootstrap folder in the app.php file, I created a function for replacing static values by using str_replace() and call this function in the same file. This is not working.
I don't want to change the static value in the controller, But on the run time.
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
function replaceHello()
{
str_replace("world","all.","Hello world");
}
replaceHello();
return $app;
This function is for replace world from the hello world to hello all in whole project.
Is there any way to do this?

Not found error on get url with additive parameters

In laravel 6 I need to run control action with url like :
http://127.0.0.1/ads/showad?wid=207ce8c0-b153-11eb-b997-4d6d53720d0c&subid=
In routes/web.php I have:
Route::get('ads/showad', 'DisplayAdController#showad')->name('show_ad');
I got not found error
I tried to modify this url definition as :
Route::get('ads/showad?wid={wid}&subid={subid?}', 'DisplayAdController#showad')->name('show_ad');
and after clearing cache running command :
php artisan route:list
I see in output :
GET|HEAD | ads/showad | show_ad | App\Http\Controllers\DisplayAdController#showad
| GET|HEAD | ads/showad?wid={wid}&subid={subid?} | show_ad | App\Http\Controllers\DisplayAdController#showad |
Anyway I got Not Found error.
How have I to modify url defintion to run url, which must be run from external apps?
Thanks!
Your second route is unnecessary.
In your controller you can access to the query parameters like this:
public function showad(Request $request) {
$request->get('wid');
}
you can also use url parameters like this:
Route::get('ads/showad/{wid}/{subid}', 'DisplayAdController#showadById')->name('show_ad_by_id');
In this case you need to do this:
public function showadById($wid, $subid) {
}

Implicit Route Model Binding returns empty model in package

I'm building a laravel package the encapsulates a rest api, and I'm running into some issues with implicit route model binding. All I'm getting back when trying to retrieve a single record is an empty array. The id that i'm trying to retrieve is present in the database (its the only record in the table) Using debugbar, it looks like its not running the query, which implies that the route binding is failing before it has a chance to run (more on that at the bottom).
api.php:
Route::apiResources([
'trackers' => TrackerController::class,
'tracker/entry' => TrackerEntryController::class,
'tracker/types' => TrackerTypeController::class
]);
pertinent artisan route:list output:
| Method | URI | Middleware |
+-----------+-----------------------+------------+
| GET|HEAD | tracker/entry/{entry} | |
| GET|HEAD | tracker/types/{type} | |
| GET|HEAD | trackers/{tracker} | |
+-----------+-----------------------+------------+
Show method from TrackerTypeController:
use Oxthorn\Trackers\Models\TrackerType as Type;
public function show(Type $type)
{
return $type;
}
So, as far as I see, my code is using the correct naming scheme for implicit route binding.
If I change the controller show method to this:
public function show(Type $type, $id)
{
$type2 = Type::findOrFail($id);
return [
[get_class($type), $type->exists, $type],
[get_class($type2), $type2->exists],
];
}
I get this output:
[
[
"Oxthorn\\Trackers\\Models\\TrackerType",
false,
[]
],
[
"Oxthorn\\Trackers\\Models\\TrackerType",
true
]
]
This seems to mimic the behavior in this StackOverflow issue: Implicit Route Model Binding, where the last posted theory was that SubstituteBindings middleware was not running. I'm not sure at this point what steps I need to take to ensure its running before my code execute, so I am here asking for advice on where to go from here.
You know, sleeping on a problem does wonders. For anyone that runs into this same issue while developing a package, I had to change my route code to this to solve the issue:
Route::apiResource('trackers', TrackerController::class)->middleware('bindings');
Route::apiResource('tracker/entry', TrackerEntryController::class)->middleware('bindings');
Route::apiResource('tracker/types', TrackerTypeController::class)->middleware('bindings');

Is there any possibility to reduce routes in laravel4

I want to know is there any possibility to reduce routes for same controller in laravel4.
Here is my route:
Route::get('emp/add-employee/','EmpController#addEmployee');
Route::post('emp/add-employee/','EmpController#addEmployee');
Route::get('emp/edit-employee/{id}','EmpController#editEmployee');
Route::post('emp/edit-employee/{id}','EmpController#editEmployee');
Route::get('emp/view-employee/{id}','EmpController#viewEmployee');
is there any posibility to do reduce...?
Your route actions look like the ones you'd find in a RESTful Resource Controller. So you could use this:
Route::resource('emp', 'EmpController', array('only' => array('create', 'store', 'edit', 'update', 'show')));
This will of course require you to rename the controller methods accordingly and the route paths will be a little different, but you'd have a more compact route definition and consistent naming. Below are the routes that are generated by the Route::resource definition above.
+-----------------------------+---------------+-------------------------+
| GET emp/create | emp.create | EmpController#create |
| POST emp | emp.store | EmpController#store |
| GET emp/{id} | emp.show | EmpController#show |
| GET emp/{id}/edit | emp.edit | EmpController#edit |
| PUT emp/{id} | emp.update | EmpController#update |
+-----------------------------+---------------+-------------------------+
So you'd have to rename your controller method names like so:
GET : addEmployee() -> create() // shows the add form
POST: addEmployee() -> store() // processes the add form when submitted
GET : editEmployee() -> edit() // shows the edit form
POST: editEmployee() -> update() // processes the edit form when submitted
GET : viewEmployee() -> show()
You could use controller routes.
Route::controller('emp', 'EmpController');
Now you just have to rename the functions within your controller to also represent the method used like this:
public function getAddEmloyee()
public function postAddEmloyee()
public function getEditEmployee($id)
etc.
See also the Laravel docs for controllers
Yes, use Route::match(). This will allow you to specify GET and POST in a single route call, like so:
Route::match(['GET', 'POST'], 'emp/edit-employee/{id}','EmpController#editEmployee');
You can also use Route::all() which will match any type request, which includes GET and POST and also any other HTTP verbs that may be specified, if that's what you want.

codeigniter: extending common controller

I've read all the post I found regarding this issue but nothing works. I'm using Codeigniter 2.02 in a LAMP with Apache2.2 and PHP5.3.2
I'm trying to create a common controller from which my common controllers will inherit so I can do common tasks there.
I have this:
file: parent_controller.php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Parent_controller extends CI_Controller {
public function Parent_controller()
{
parent::__construct();
}
public function index() {
echo "Hi!";
}
}
file: welcome.php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends Parent_controller {
public function __construct()
{
parent::__construct();
}
}
I've tried the next solutions I've found, but none of them are working:
public function __contstruct() instead of public function Parent_controller()
parent::Parent_controller();
put the parent_controller.php file into core
put the parent_controller.php file into controllers
adding this to config/config.php:
function __autoload($class){
if (file_exists(APPPATH."(controllers|core)/".$class.EXT)){
require_once(APPPATH.'(controllers|core)/'.$class.EXT);
}
}
Thank you all.
Take a look at this post from Phil Sturgeon:
http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY
The key is using the native autoload as explained in his post:
/*
| -------------------------------------------------------------------
| Native Auto-load
| -------------------------------------------------------------------
|
| Nothing to do with cnfig/autoload.php, this allows PHP autoload to work
| for base controllers and some third-party libraries.
|
*/
function __autoload($class)
{
if(strpos($class, 'CI_') !== 0)
{
#include_once( APPPATH . 'core/'. $class . EXT );
}
}
NOTE
As a note, you'll want to put all of your "base" controllers in the core folder for CI2+
This bit is correct
public function __contstruct() instead of public function
Parent_controller()
But what you're looking for is the MY_ prefix. So if you create the controller in the /application/libraries/ folder and call the file MY_Controller.php and the class MY_Controller it'll work.
You can also change the MY_ prefix to whatever you'd like in the config.php file. Look for:
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
For further reading and a more depth explanation see http://codeigniter.com/user_guide/general/core_classes.html
Also note it doesn't load a multitude of files. It simply looks for 1 controller called MY_Controller.php.
If you are thinking it will load MY_Test_Controller.php and MY_Web_Controller.php, it won't.
If you can include multiple controllers in that one file, or include other files from that file.
You could build around this of course, but a good bit of extra information to know.

Resources