Laravel debugging 404 routes - php

Ok, the full routes.php file that I use... I just pasted it here: http://pastebin.com/kaCP3NwK
routes.php
//The route group for all other requests needs to validate admin, model, and add assets
Route::group(array('before' => 'validate_admin|validate_model'), function()
{
//Model Index
Route::get('admin/(:any)', array(
'as' => 'admin_index',
'uses' => 'admin#index'
));
administrator config:
...
'models' => array(
'news' => array(
'title' => 'News',
'single' => 'news',
'model' => 'AdminModels\\News',
),
...
links generator:
#foreach (Config::get('administrator.models') as $key => $model)
#if (Admin\Libraries\ModelHelper::checkPermission($key))
<?php $key = is_numeric($key) ? $model : $key; ?>
<li>
{{ HTML::link(URL::to_route('admin_index', array($key)), $model['title']) }}
</li>
#endif
#endforeach
controllers/admin.php
public function action_index($modelName)
{
//first we get the data model
$model = ModelHelper::getModelInstance($modelName);
$view = View::make("admin.index",
array(
"modelName" => $modelName,
)
);
//set the layout content and title
$this->layout->modelName = $modelName;
$this->layout->content = $view;
}
So, when accessing http://example.com/admin/news the news is sent to action_index... but for some reason it doesn't get there and it returns 404

Notice that I defined the following 'model' => 'AdminModels\\News',
when actually my namespace register was Admin\Models, so setting it to 'model' => 'Admin\Models\\News', for my issue for the 404

Routes are evaluated in the order that they're registered, so the (:any) route should be last. You're being sent (I think) to admin#index -- if that function isn't defined yet, that's why you're getting a 404.

Not related to the question, but if anyone (like me) comes here to find clues why a Laravel application displays a 404, here are some reasons:
Models not found in database that are specified in the URL
You have setup incorrect route model bindings in RouteServiceProvider (as I did when I stumbled over this answer). Example: Route::model('user', Tenant::class); when it should be User::class
Some middleware returns 404 (e.g. via "abort(404)")
The corresponding controller returns 404
The controller method (or namespace) is not found (This is the answer for this question.)

Related

Policy with route group keeps returning 403

I'm trying to use policy on a route group. I've included the bindings middleware and tried to list the ACTION and MODEL in the CAN middleware.
For some reason it keeps returning 403. Probably I didn't quite understood how the policies work.
I'm trying to enter the before method in the policy but It keeps returning 403. Also it would be lovely if someone explains how exactly should I list custom methods in the middleware.
I also did register my policy in the AuthServiceProvider
protected $policies = [
Service::class => ServicePolicy::class,
];
public function before(CustomAuth0User $user, Service $service)
{
dd($service);
}
Route::group(['prefix' => 'services', 'namespace' => 'Services', 'middleware' => ['bindings', 'can:getCancel, service']], function () {
Route::get('/{service}/cancel', 'ServiceController#getCancel');
Route::post('/{service}/cancel', 'ServiceController#postCancel');
Route::get('/{id}/reassign', 'ServiceController#getReassign');
Route::post('/{id}/reassign', 'ServiceController#postReassign');
Route::get('/{id}/close', 'ServiceController#getClose');
Route::post('/{id}/close', 'ServiceController#postClose');
Route::get('/{id}/history', 'ServiceController#getHistory');
});
Controller
public function getCancel(Service $service)
{
dd($service);
}

Accessing route for form submit in Laravel

i am trying to access one route like pages.trashmultiple this in my view. But its throwing error of Route [pages.trashmultiple] not defined.. Here is how my view looks like:
{!!Form::open([
'method' => 'put',
'route' => 'pages.trashmultiple'
])!!}
<th class="table-checkbox">
<input type="checkbox" class="group-checkable" data-set="#sample_3 .checkboxes"/>
</th>
{!!Form::close()!!}
This is how my controller looks like:
public function trashmultiple(Request $request){
//return "trash multiple page";
return Input::all();
}
And this is how my routes look like:
Route::group(['middleware' => ['web']], function () {
Route::get('pages/trash', 'PagesController#trashpage');
Route::get('pages/movetotrash/{id}', 'PagesController#movetotrash');
Route::get('pages/restore/{id}', 'PagesController#restore');
Route::get('pages/trashmultiple', 'PagesController#trashmultiple'); //this is not working
Route::resource('pages', 'PagesController');
});
When i load my url http://localhost:8888/laravelCRM/public/pages it shows me this below error:
ErrorException in UrlGenerator.php line 307:
Route [pages.trashmultiple] not defined. (View: /Applications/MAMP/htdocs/laravelCRM/resources/views/pages/pages.blade.php)
I want to know why i am unable to access the pages.trashmultiple when i have already defined it.
Is there any way i can make it accessible through pages.trashmultiple?
Thank you! (in advance)
chnage your route to like this:
Route::get('pages/trashmultiple', 'PagesController#trashmultiple');
To
Route::get('pages/trashmultiple', [
'as' => 'pages.trashmultiple', 'uses' => 'PagesController#trashmultiple'
]);
Change your route so that it becomes:
Route::get('pages/trashmultiple',
['as'=>'pages.trashmultiple',
'uses'=>'PagesController#trashmultiple']);

Zend Framework 2: Navigation

In my controller I create the Navigation object and passing it to the view
$navigation = new \Zend\Navigation\Navigation(array(
array(
'label' => 'Album',
'controller' => 'album',
'action' => 'index',
'route' => 'album',
),
));
There trying to use it
<?php echo $this->navigation($this->navigation)->menu() ?>
And get the error:
Fatal error: Zend\Navigation\Exception\DomainException: Zend\Navigation\Page\Mvc::getHref cannot execute as no Zend\Mvc\Router\RouteStackInterface instance is composed in Zend\View\Helper\Navigation\AbstractHelper.php on line 471
But navigation which I use in layout, so as it is written here: http://adam.lundrigan.ca/2012/07/quick-and-dirty-zf2-zend-navigation/ works. What is my mistake?
Thank you.
The problem is a missing Router (or to be more precise, a Zend\Mvc\Router\RouteStackInterface). A route stack is a collection of routes and can use a route name to turn that into an url. Basically it accepts a route name and creates an url for you:
$url = $routeStack->assemble('my/route');
This happens inside the MVC Pages of Zend\Navigation too. The page has a route parameter and when there is a router available, the page assembles it's own url (or in Zend\Navigation terms, an href). If you do not provide the router, it cannot assemble the route and thus throws an exception.
You must inject the router in every page of the navigation:
$navigation = new Navigation($config);
$router = $serviceLocator->get('router');
function injectRouter($navigation, $router) {
foreach ($navigation->getPages() as $page) {
if ($page instanceof MvcPage) {
$page->setRouter($router);
}
if ($page->hasPages()) {
injectRouter($page, $router);
}
}
}
As you see it is a recursive function, injecting the router into every page. Tedious! Therefore there is a factory to do this for you. There are four simple steps to make this happen.
STEP ONE
Put the navigation configuration in your module configuration first. Just as you have a default navigation, you can create a second one secondary.
'navigation' => array(
'secondary' => array(
'page-1' => array(
'label' => 'First page',
'route' => 'route-1'
),
'page-2' => array(
'label' => 'Second page',
'route' => 'route-2'
),
),
),
You have routes to your first page (route-1) and second page (route-2).
STEP TWO
A factory will convert this into a navigation object structure, you need to create a class for that first. Create a file SecondaryNavigationFactory.php in your MyModule/Navigation/Service directory.
namespace MyModule\Navigation\Service;
use Zend\Navigation\Service\DefaultNavigationFactory;
class SecondaryNavigationFactory extends DefaultNavigationFactory
{
protected function getName()
{
return 'secondary';
}
}
See I put the name secondary here, which is the same as your navigation key.
STEP THREE
You must register this factory to the service manager. Then the factory can do it's work and turn the configuration file into a Zend\Navigation object. You can do this in your module.config.php:
'service_manager' => array(
'factories' => array(
'secondary_navigation' => 'MyModule\Navigation\Service\SecondaryNavigationFactory'
),
)
See I made a service secondary_navigation here, where the factory will return a Zend\Navigation instance then. If you do now $sm->get('secondary_navigation') you will see that is a Zend\Navigation\Navigation object.
STEP FOUR
Tell the view helper to use this navigation and not the default one. The navigation view helper accepts a "navigation" parameter where you can state which navigation you want. In this case, the service manager has a service secondary_navigation and that is the one we need.
<?= $this->navigation('secondary_navigation')->menu() ?>
Now you will have the navigation secondary used in this view helper.
Disclosure: this answer is the same as I gave on this question: https://stackoverflow.com/a/12973806/434223
btw. you don't need to define controller and action if you define a route, only if your route is generic and controller/action are variable segments.
The problem is indeed that the routes can't be resolved without the router. I would expect the navigation class to solve that issue, but obviously you have to do it on your own. I just wrote a view helper to introduce the router with the MVC pages.
Here's how I use it within the view:
$navigation = $this->navigation();
$navigation->addPage(
array(
'route' => 'language',
'label' => 'language.list.nav'
)
);
$this->registerNavigationRouter($navigation);
echo $navigation->menu()->render();
The view helper:
<?php
namespace JarJar\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\View\Helper\Navigation;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Navigation\Page\Mvc;
class RegisterNavigationRouter extends AbstractHelper implements ServiceLocatorAwareInterface
{
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function __invoke(Navigation $navigation)
{
$router = $this->getRouter();
foreach ($navigation->getPages() as $page) {
if ($page instanceof Mvc) {
$page->setRouter($router);
}
}
}
protected function getRouter()
{
$router = $this->getServiceLocator()->getServiceLocator()->get('router');
return $router;
}
}
Don't forget to add the view helper in your config as invokable instance:
'view_helpers' => array(
'invokables' => array(
'registerNavigationRouter' => 'JarJar\View\Helper\RegisterNavigationRouter'
)
),
It's not a great solution, but it works.

How to generate URL using Module, controller and view?

Is there a way of generating a full url in zend if the Module, controller and view names are known?
I'm assuming you mean module, controller, and action, since the view is determined by the action (usually).
In the view:
echo $this->url(array('module' => $module,
'controller' => $controller,
'action' => $action));
Any parameters not set, default to the current values, so in any given view:
echo $this->url(); //link for the current request
The function also accepts two additional arguments: url($urlOptions, $name, $reset). $name allows you to specify a route name, and $reset will clear the generated URL of any current parameters.
In the controller:
This actually isn't documented, but follows the structure of the redirector helper (in fact, I believe it is used by the redirector helper):
$url = $this->getHelper('url')->simple($action, $controller, $module, $params);
You can also use the url() method, which follows the View helper:
$url = $this->getHelper('url')->url(array('module' => $module,
'controller' => $controller,
'action' => $action));

CakePHP - admin routing for /admin/, but not all the rest (way to set default admin false?)

I read the tutorial, and found that to use the "admin" prefix, you can just uncomment the:
Configure::write('Routing.prefixes', array('admin'));
config/core.php file.
I did that, and my admin routing works great - /admin/users/add hits the admin_add() function in my users_controller.
The problem is - it's also changing my normal links - ie. my "LOGOUT" button now tries to go to /admin/users/logout instead of just /users/logout. I realize I can add 'admin'=>false, but I'd rather not have to do that for every link in my site.
Is there a way to make it so ONLY urls with either 'admin'=>true or /admin/... to go to the admin, and NOT all the rest of the links?
Expanding on user Abba Bryant's edit, have a look at how to create a helper in the cook book : http://book.cakephp.org/view/1097/Creating-Helpers
If having to disable routing manually on all your links is an annoyance (it would be to me!), you could create a new helper MyCustomUrlHelper (name doesn't have to be that long of course), and have it use the core UrlHelper to generate the URLs for you.
class MyCustomUrlHelper extends AppHelper {
public $helpers = array('Html');
function url($controller, $action, $params ,$routing = false, $plugin = false) {
//Example only, the params you send could be anything
$opts = array(
'controller' => $controller,
'action' => $action
//....
);
}
//another option
function url($params) {
//Example only, the params you send could be anything
$opts = array(
'controller' => $params['controller'],
'action' => $params['action']
//....
)
}
//just fill up $opts array with the parameters that core URL helper
//expects. This allows you to specify your own app specific defaults
return $this->Html->url($opts); //finally just use the normal url helper
}
Basically you can make it as verbose or terse as you want. It's just a wrapper class for the the actual URL helper which will do the work from inside. This allows you to give defaults that work for your specific application. This would also allow you to make a change in one place and have the routing for the whole application be updated.
EDIT
You could also check whether the passed $opts array is a string. This way you can have the best of both worlds.
Make sure if you use the prefix routing that you handle it in the HtmlHelper::link calls like so
<?php
...
echo $html->link( array(
'controller' => 'users',
'action' => 'logout',
'plugin' => false,
'admin' => false,
));
...
?>
** EDIT **
You could extend the url function in your AppHelper to inspect the passed array and set the Routing.prefixes keys to false if they aren't already set in the url call.
You would then need to specify the prefix in your admin links every time.
The HtmlHelper accepts two ways of giving the URL: it can be a Cake-relative URL or an array of URL parameters.
If you use the URL parameters, by default if you don't specify the 'admin' => false parameter the HtmlHelper automatically prefixes the action by 'admin' if you are on an admin action.
IMHO, the easiest way to get rid off this parameter is to use the Cake-relative URL as a string.
<?php
//instead of using
//echo $this->Html->link(__('logout', true), array('controller' => 'users', 'action' => 'logout'));
//use
echo $this->Html->link(__('logout', true), '/users/logout');
Kind regards,
nIcO
I encountered this problem this week and this code seemed to fix it. Let me know if it doesn't work for you and I can try to find out what else I did to get it to work.
$this->Auth->autoRedirect = false;
$this->Auth->loginAction = array(Configure::read('Routing.admin') => false, 'controller' => 'users', 'action' => 'login');
$this->Auth->logoutRedirect = array(Configure::read('Routing.admin') => false, 'controller' => 'users', 'action' => 'logout');
$this->Auth->loginRedirect = array(Configure::read('Routing.admin') => false, 'controller' => 'users', 'action' => 'welcome');
This was really frustrating, so I'm glad to help out.
I'm late to the party, but I have a very good answer:
You can override the default behavior by creating an AppHelper class. Create app/app_helper.php and paste the following:
<?php
class AppHelper extends Helper{
function url($url = null, $full = false) {
if(is_array($url) && !isset($url['admin'])){
$url['admin'] = false;
}
return parent::url($url, $full);
}
}
?>
Unless it is specified when you call link() or url(), admin will be set to false.

Categories