Laravel: Can I add custom method to API Controller that routed by api.php?

Shintaro Nomiya :

I know I can easily create API in laravel, like below.

Http/Controllers/Api/MyApiController.php
use App\Model\MyModel;

class MyApiController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $models = MyModel::all();
        return $models;
    }

    ....

routes/api.php
Route::group(['middleware' => ['api']], function(){
    Route::resource('myTable', 'Api\MyApiController');
});

But it seems that it has only basic CRUD methods. Is there a way to add custom method and call it by some Http requests? I mean, If I added my own method like as follows:

    public function myMethod()
    {
        $models = MyModel::all()->where('id', '>', 100)->get();
        return $models;
    }

I want to use it by such a request as GET /api/MyMethod/{id}. Does anyone know any ways without adding route to web.php?
thanks.

tamrat :

You can. You just need to define those routes in your routes/api.php file.

routes/api.php
Route::group(['middleware' => ['api']], function(){
    Route::resource('myTable', 'Api\MyApiController');

    // Define new routes like this
    Route::get('myTable/MyMethod/{id}', 'Api\MyApiController@myMethod');
});

Update

Even though its perfectly fine to define routes with custom method names (other than the basic CRUD ones) in such a way, it can often lead to overpopulated controllers. Check out this interesting talk by Adam Wathan about this issue.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198631&siteId=1