How to do restful ajax routes to methods in Laravel 5?

12,356

Solution 1

After inspection of Laravel's Http Request and Route classes, I found the route() and setAction() methods could be useful.

So I created a middleware to handle this:

<?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);
    }

} 

Now my route looks like:

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

And correctly hits my controller methods (without disturbing Laravel's normal flow):

<?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!');
    }
    ...

I think this is a fairly clean solution.

Solution 2

You can't make this dispatch in the routing layer if you keep the same URL. You have two options :

  1. Use different routes for your AJAX calls. For example, you can prefix all your ajax calls by /api. This is a common way :

    Route::group(['prefix' => 'api'], function()
    {
    
        Route::get('items', function()
        {
            //
        });
    
    });
    
  2. If the only different thing is your response format. You can use a condition in your controller. Laravel provides methods for that, for example :

    public function index()
    {
        $items = ...;
    
        if (Request::ajax()) {
            return Response::json($items);
        } else {
            return View::make('items.index');
        }
    }
    

You can read this http://laravel.com/api/5.0/Illuminate/Http/Request.html#method_ajax and this http://laravel.com/docs/5.0/routing#route-groups if you want more details.

Share:
12,356
prograhammer
Author by

prograhammer

David Graham Developing web applications for The Home Depot.

Updated on June 07, 2022

Comments

  • prograhammer
    prograhammer almost 2 years

    So I have a route that looks like this:

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

    However, I also have ajax calls at the same URL (using a request parameter called ajax like: some/page/?ajax=my_action) that I want to hit methods on my controller:

    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
    ...
    

    What's the elegant solution to setting this up in my routes.php file?