Custom Error Pages for particular controllers in CodeIgniter - codeigniter

If we call a method abc() within a controller named Example. Suppose abc() is not present in Example controller.
In such cases i need to display a custom error message instead of
404 Page Not Found
The page you requested was not found.
for this particular controller only.
I know we can set custom error pages, but it applies to all controller.
I need to use it with one controller only.
For Eg:
class Example extends CI_Controller
{
function index()
{
echo "index page";
}
function xyz()
{
echo "xyz page";
}
}
if i call example/xyz it displays output as 'xyz page'
but if i call example/abc it show page not found error. (i need custom message for this controller only).
Thank You...

You can do something similar to below. If the method exists call it otherwise display your own error message.
function _remap( $method )
{
// $method contains the second segment of your URI
if(method_exists($this, $method ) )
{
$this->$method();
}
else
{
//your custom coding here
}
}

Related

How do I send data to partial views from controller in laravel?

I have setup my navigation menu from a ViewComposer (see laravel view composers: https://laravel.com/docs/5.6/views#view-composers) like this
View::composer('partials.nav', function ($view) {
$view->with('menu', Nav::all());
});
What I need is that from some controllers to setup which navigation item is active, ie "current section".
Question:
How do I send from some controllers a variable to "partials.nav" like currentNavItem?
Do I send it with the rest of the variables for returned view?
like
return view('page.blade.php",$viewVariables + $optionalVariablesForPartialsViews);
It looks spammy
Side notes:
I use laravel 5.6
Later edit
It looks Laravel 5.1 : Passing Data to View Composer might be an options. I will try and get back .
Because the $variable you want to send differs in different controller's actions yes you need to specify the $variable
return view('page.blade.php",$viewVariables,$variablesForPartialsViews);
of course you might need to set a default value for the $variable in order to avoid undefined variable error
You should handle the parameters.
for exemple:
public function compose(View $view)
{
$view->with('page', $this->getPage());
}
public function getPage()
{
$viewVariables = 2;
$optionalVariablesForPartialsViews = 1;
return $viewVariables + $optionalVariablesForPartialsViews;
}
Under your app folder make a class named yourClassNameFacade. Your class would look like this.
class yourClassNameFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'keyNameYouDecide';
}
}
Then go to the file app/Providers/AppServiceProvider.php and add to the register function
public function register()
{
$this->app->bind('keyNameYouDecide', function (){
//below your logic, in my case a call to the eloquent database model to retrieve all items.
//but you can return whatever you want and its available in your whole application.
return \App\MyEloquentClassName::all();
});
}
Then in your view or any other place you want it in your application you do this to reference it.
view is the following code:
{{ resolve('keyNameYouDecide') }}
if you want to check what is in it do this:
{{ ddd(resolve('keyNameYouDecide')) }}
anywhere else in your code you can just do:
resolve('keyNameYouDecide'))

How to get controller action by passing URL in laravel

I searched more time to find how to get the controller method name by passing the URL but not found my expected answer. I want to make a method where I will pass a URL and it will give the corresponding controller action like as below but I can't figure out.
I found a helper which just return the current URL's action which is Route::currentRouteAction()
If a route in my application like as Route::get('/abc', 'YourController#method') which will generate the url http://example.com/abc
then how can I get the YourController#method by passing http://example.com/abc
function getAction($url){
//what will be logic?
// return like App\Controllers\MyController#method
}
I have to make a custom permission system where I need it for show and hide the menu by checking the URL of each menu.
Within your controller you can do the following:
<?php
use Illuminate\Routing\Router;
use Illuminate\Http\Request;
public function index(Request $request, Router $route)
{
$action = $router->getRoutes()->match($request)->getActionName();
// action should be what you're looking for.
}
You can try this if you want to:
Route::get('/the/url', 'YourController#method');
Every time anything calls the URL in the route, your method will be called.
You don't need to navigate to that url to call your method, it could be called by a form action, or a buttons action and just execute your method.
Edit:
url is your url as parameter (plain route)
import this:
use Illuminate\Routing\Route;
this is your function:
public function method(Route $route, $url)
{
$routes = \Route::getRoutes()->getRoutes();
foreach($routes as $r){
if($r->getUri() == $url){
$youraction= $r->getActionName();
dd($youraction);
}
else{
dd('does not exist');
}
}
}
Tested.

Laravel 4: Responding to AJAX requests from controller

I'm trying to generate ajax specific responses from my controllers by using the Request::ajax() method, which is working just fine. The only problem is that the way I have it set up right now isn't really a nice looking solution.
My controller:
class HomeController extends BaseController {
protected $layout = 'layouts/main';
public function __construct()
{
$this->beforeFilter('auth');
}
public function getIndex()
{
$view = View::make('content.home.index');
if(Request::ajax()) return $view; //For ajax calls we only want to return the content to be placed inside our container, without the layout
$this->layout->menu = 'content.menu';
$this->layout->content = $view;
}
}
So right now, for every method I define within my controllers I need to add the code snippet that checks for an AJAX request and returns a single view if the statement returns true.
This leads to my question that is probably more PHP related than it is to the framework;
Is there a way of executing my AJAX check on every method call, without actually placing it inside the method? Or is there some other solution to keep my code DRY?
Thanks in advance!
PS: This is my first post on stackoverflow, so feel free to correct me if I made any mistakes
Create a new barebone layout named 'layouts/ajax' (or any name you like).
<?php echo $content ?>
In your Base controller, override this setupLayout() function.
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$layout = Request::ajax() ? 'layouts/ajax' : $this->layout;
$this->layout = View::make($layout);
}
}
Change your getIndex() function to this.
public function getIndex()
{
$view = View::make('content.home.index');
$this->layout->menu = 'content.menu';
$this->layout->content = $view;
}
Now non-ajax requests will be rendered using layout set in the controller, where as ajax requests will receive whatever set to $this->layout->content.
Note : Controller will neglect the layout setup in setupLayout(), if the called method returns truthy value. So this method will not work for functions like below.
public function getIndex()
{
return View::make('content.home.index');
}
You could just change the layout property, in the constructor, if it's an ajax request:
public function __construct()
{
$this->beforeFilter('auth');
if(Request::ajax()) {
$this->layout = '';
}
}
If it doesn't work try setting it to NULL instead.
Why would you return a VIEW via ajax? Are you using it to create a SPA? If so there are better ways. I'm generally against returning HTML via AJAX.
The route I'd go in your position is probably opposite of how you're doing it. Render the view no matter what, if the request is ajax, pass the extra data back and have JS render the data on the page. That's essentially how most Javascript MVC frameworks function.
Sorry if I am totally missing the point here, just going on an assumption of your end goal with the info you provided.

Codeigniter Controller URI routing problems

I encounter problems when I call the method of a controller. By the way, this controller is routed.
Routes
$route['admin/company'] ='company';
Controller
class Company extends CI_controller {
public function __construct() {
parent::__construct();
session_start();
/** Check if user is logged in */
if ($this->session->userdata('user') != "") {
$this->load->model('my_model');
if ( $this->uri->segment(1) != "admin" ) {
redirect('admin/company/'.$this->uri->segment(2));
}
} else redirect('/');
}
public function index() { Some coding here............ }
public function addnew() { Some coding here...........}
public function process() { Some coding here...... }
}
When I call "localhost/company", it works fine and redirects me to "localhost/admin/company which is great. But, when I try to call the method of it, it displays a 404 error message.
Example: When I go to link: localhost/admin/company/addnew
Did lack something in routes? or in controller? or anything else?
Thanks,
James
If appropriate for all use cases, use a simple catch-all rule in routes.php:
$route['admin/company/(.+)$'] = "company/$1";
You will have to add a route for each function in your controller.
$route['admin/company/addNew'] ='company/addNew';
$route['admin/company/process'] ='company/process';
It's very annoying. Better, create a folder "admin" inside your "controllers" folder. Put the controller on the folder. Thus you can access your controller with the URL "localhost/admin/company" and all the methods without rerouting.
If it doesn't work at first, create a controller inside "admin" folder with the same name you'll find in your routes file (default_controller).
create a admin directory and add $route["company"]="admin/company"

post the form and again load the view ,best suggested way

Till now i am using the form post method like this::
controller ::
public function loading_view()
{
.
.
.
.
$this->load->view('abc');
}
view abc:
">
when this form posted it will redirected to
public function method_of_controller()
{
.
//perform query
.
// here i am havin 2 way to call
//1.
$this ->load->view('abc');
//and 2.
load->loading_view();
}
//bu url remain same after the post method like ....index.php/loading_view
and but on reloading the page again the query runs fr 2nd method of loading view
so which way you will suggest me to use best
1- If you are not passing data to your view and your view is just contains html and javascript
than first method is beter.
2- if you are passing data to our abc view page than second is beter.
3- beter way is to make another view for this part for portability
because in some point you will reach you make changes so it is beter to each should be
separate.
yes you can post data to save view, without changing url redirection, in following way
controller
class PostTest extends CI_Controller{
public function loading_view()
{
$this->form_validation->rules('name','Name','required');
if(!$this->form_validation->run()){
$this->load->view('abc');
}
else{
$name = $this->input->post('name');
}
}
}
now here is most interesting part is view in form action you need to use uri_string() method like this
view
<? echo form_open(uri_string())
.form_input('name').br()
.form_error('name')
.form_submit('submit','Post data');
?>

Resources