Laravel 5.4: api route list

I have the following lines in routes/api.php

Route::middleware('api')->get('/posts', function (Request $request) {
    Route::resource('posts','ApiControllers\PostsApiController');
});

      

When I clicked http://localhost:8000/api/posts

it goes back to its original state, but when I move the above route in routes/web.php

like this:

Route::group(['prefix' => 'api/v1'],function(){
    Route::resource('posts','ApiControllers\PostsApiController');
});

      

it works.

As a reminder, I cleared the routes cache file with php artisan route:clear

, and the list of routes comes with php artisan route:list

when mine is routes/web.php

empty, and routes/api.php

has the above route:

+--------+----------+-------------+------+---------+------------+
| Domain | Method   | URI         | Name | Action  | Middleware |
+--------+----------+-------------+------+---------+------------+
|        | GET|HEAD | api/posts   |      | Closure | api        |
+--------+----------+-------------+------+---------+------------+

      

Note that with the web routes part, the list comes up fine and works fine.

What am I doing wrong here?

+3


source to share


1 answer


Don't use middleware api

and see the following route example for API routes.

Example 1 (in your api.php)

Route::get('test',function(){
    return response([1,2,3,4],200);   
});

      

visit this route as

localhost/api/test

      

Example 2 (if you want api authentication, token authentication using laravel passport)

Route::get('user', function (Request $request) {
    ///// controller
})->middleware('auth:api');

      



You can make a request for this route, but you need to pass the access token as the middleware was used auth:api

.

Note: see /app/http/kernel.php

and you can find

protected $routeMiddleware = [
//available route middlewares
]

      

This file (kernel.php) should not have this type (api) of middle class (kernel.php) unless you create one, so you cannot use middleware like api

.

Here's how I create a REST API (api.php)

//All routes goes outside of this route group which does not require authentication
Route::get('test',function(){
    return response([1,2,3,4],200);

});
//following Which require authentication ................
Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function(){
    Route::get('user-list',"Api\ApiController@getUserList");
    Route::post('send-fax', [
        'uses'=>'api\ApiController@sendFax',
        'as'=>'send-fax'
    ]);
    Route::post('user/change-password', [
        'uses'=>'api\ApiController@changePassword',
        'as'=>'user/change-password'
    ]);

});

      

+7


source







All Articles