简体   繁体   English

Laravel 6 路由变量控制器方法

[英]Laravel 6 route variable Controller method

I want to make one route for all my ajax requests in laravel.我想为 laravel 中的所有 ajax 请求制定一条路线。 Currently what I have is:目前我所拥有的是:

Route::post('/ajax/{method}', 'AjaxController@index')->name('ajax-request');

Can I do something like this (using dynamic method name):我可以这样做吗(使用动态方法名称):

Route::post('/ajax/{method}', 'AjaxController@{method}')->name('ajax-request');

so for example when I call /ajax/get_comments , it will call AjaxController@get_comments method ?例如,当我调用/ajax/get_comments ,它会调用AjaxController@get_comments方法?

You can add closure function to your route to achieve this one.您可以在您的路线中添加闭包功能来实现这一目标。

Route::get('ajax/{method}', function($method){

    $app = app();

    $controller = $app->make('App\Http\Controllers\AjaxController');

    return $controller->callAction($method, $parameters = array());

});

Now, call the get_comments method like:现在,调用get_comments方法,如:

localhost:8000/ajax/get_comments

NOTE: make sure your controller is inside app/Http/Controller/ directory.注意:确保您的控制器位于app/Http/Controller/目录中。

I hope you understand我希望你明白

The Route methods( get , post etc) can accept their's second parameter as string using the following pattern ControllerName@methodName . Route 方法( getpost等)可以使用以下模式ControllerName@methodName将其第二个参数作为字符串接受。

You could retrieve the {method} parameter from request path and append it to Route method's second parameter.您可以从请求路径中检索{method}参数并将其附加到 Route 方法的第二个参数。 ie, like 'ControllerName@'. 'methodName'即,像'ControllerName@'. 'methodName' 'ControllerName@'. 'methodName'

Try the following :尝试以下操作

Assuming {method} would be your second segment in the request path.假设{method}将是请求路径中的第二段。 [If not change the value in the segment() parameter.] [如果不更改segment()参数中的值。]

Try the following:请尝试以下操作:

Route::post('/ajax/{method}', 'AjaxController@'.(Request::segment('2')))->name('ajax-request');

Please Note :请注意

If you choose to put URL parameter to be used as the method name there are some chance that, if a user is able to change the request path other than the specified one, run time exceptions will be thrown.如果您选择将 URL 参数用作方法名称,那么如果用户能够更改指定路径以外的请求路径,则可能会引发运行时异常。

Consider the following scenario :考虑以下场景:

Your AjaxController has only methods get_comments() and get_deleted_comments() .您的AjaxController只有方法get_comments()get_deleted_comments()

If the request is /ajax/get_comments or /ajax/get_deleted_comments then their corresponding methods will work.如果请求是/ajax/get_comments/ajax/get_deleted_comments那么它们对应的方法将起作用。 But if request is something like /ajax/get_xyz and you dont have a method named get_xyz in your AjaxController then a BadMethodCallException will be thrown.但是,如果请求类似于/ajax/get_xyz并且您的AjaxController没有名为get_xyz的方法,则将抛出BadMethodCallException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM