检查是否定义了Laravel Controller Action [英] Check whether Laravel Controller Action is defined

查看:103
本文介绍了检查是否定义了Laravel Controller Action的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它将在数据库中存储链接,允许用户为链接分配操作.我想避免不存在该操作并且收到此错误的情况;

I have an application where I will be storing links in the database allowing the user to assign actions to the link. I want to avoid the situation where the action does not exist and I get this error;

未定义操作App \ Http \ Controllers \ PermissionController @ index2.

Action App\Http\Controllers\PermissionController@index2 not defined.

所以我想检查一个动作是否存在并具有路由.如果可能的话,可以在刀片服务器上使用,但其他任何地方都可以.

So I would like to check whether an action exists and has route. If possible in blade but anywhere else is fine.

推荐答案

没有任何内置方法可以做到这一点.但是我们有一个action辅助方法,该方法根据控制器的动作生成路由URL.我们可以利用它并创建一个简单的辅助函数来达到相同的结果.该方法还会检查给定的控制器方法是否链接到路由,因此它完全可以满足您的需求.

There isn't any built in way to do this. But we have a action helper method which generates route url based on the controller action. We can make use of this and create a simple helper function to achieve the same result. The method also checks if the given controller method is linked to a route, so it does exactly what you need.

function action_exists($action) {
    try {
        action($action);
    } catch (\Exception $e) {
        return false;
    }

    return true;
}

// Sample route
Route::get('index', 'TestController@index');

$result = action_exists('TestController@index');
// $result is true

$result = action_exists('TestController@index1');
// $result is false

您还可以直接使用该类来验证action方法的存在,但是如果该方法存在但未链接到路线,则返回true.

You could also verify the existence of the action method using the class directly, but this would return true if the method exists but isn't linked to a route.

这篇关于检查是否定义了Laravel Controller Action的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆