编程语言
首页 > 编程语言> > php – 如何在Laravel 5中使用restful ajax路由到方法?

php – 如何在Laravel 5中使用restful ajax路由到方法?

作者:互联网

所以我有一条看起来像这样的路线:

Route::any('some/page', ['as' => 'some-page', 'uses' => 'SomePageController@index']);

但是,我也在同一个URL上使用ajax调用(使用名为ajax的请求参数:some / page /?ajax = my_action),我想在我的控制器上点击方法:

index                   already routes:   'SomePageController@index'
ajax = my_action        needs to route:   'SomePageController@ajaxMyAction'
ajax = my_other_action  needs to route:   'SomePageController@ajaxMyOtherAction'
ajax = blah_blah        needs to route:   'SomePageController@ajaxBlahBlah
...

在我的routes.php文件中设置它的优雅解决方案是什么?

解决方法:

在检查了Laravel的Http请求和路由类之后,我发现route()setAction()方法可能很有用.

所以我创建了一个中间件来处理这个:

<?php namespace App\Http\Middleware;

class Ajax {

    public function handle($request, Closure $next)
    {
        // Looks for the value of request parameter called "ajax"
        // to determine controller's method call
        if ($request->ajax()) {
            $routeAction = $request->route()->getAction();
            $ajaxValue = studly_case($request->input("ajax"));
            $routeAction['uses'] = str_replace("@index", "@ajax".$ajaxValue, $routeAction['uses']);
            $routeAction['controller'] = str_replace("@index", "@ajax".$ajaxValue, $routeAction['controller']);
            $request->route()->setAction($routeAction);
        }

        return $next($request);
    }

} 

现在我的路线看起来像:

Route::any('some/page/', ['as' => 'some-page', 'middleware'=>'ajax', 'uses' => 'SomePageController@index']);

并正确点击我的控制器方法(不会打扰Laravel的正常流程):

<?php namespace App\Http\Controllers;

class SomePageController extends Controller {

    public function index()
    {
        return view('some.page.index');
    }

    public function ajaxMyAction(Requests\SomeFormRequest $request){
        die('Do my action here!');
    }

    public function ajaxMyOtherAction(Requests\SomeFormRequest $request){
        die('Do my other action here!');
    }
    ...

我认为这是一个相当干净的解决方案.

标签:php,ajax,laravel,laravel-5,restful-architecture
来源: https://codeday.me/bug/20190623/1275208.html