简体   繁体   中英

method post, put, delete route not work on laravel 5

I try test api rest on laravel 5 but I have problems with method post, put, delete.
In my route.php file I have code:

Route::group(['prefix' => 'api'], function()
{
    Route::group(['prefix' => 'user'], function()
    {
        Route::get('', ['uses' => 'UserController@allUsers']);

        Route::get('{id}', ['uses' => 'UserController@getUser']);

        Route::post('', ['uses' => 'UserController@saveUser']);

        Route::put('{id}', ['uses' => 'UsercCntroller@updateUser']);

        Route::delete('{id}', ['uses' => 'UserController@deleteUsers']);

    });
});

Route::get('/', function()
{
    return 'Enjoy the test...';
});

and in UserController.php have code:

public function allUsers()
{
   return 'test';
}

public function getUser($id)
{
    return 'test get user';
}

public function saveUser()
{
    return 'test save user';
}

public function updateUser($id)
{
    return 'test update user';
}

public function deleteUsers($id)
{
    return 'test delete user';
}

When I run with method get it works good but with method post, put and delete it does not work.
Why is this?

If you want to make REST APIs then use laravel's generators.

Use php artisan make:controller UserController

Laravel automatically creates RESTful controller class for you with all required methods.

Then just put one line in your routes.php

Route::group(['prefix' => 'api'], function()
{
    Route:resource('user', 'UserController');
});

And that's it, now you can access get, post, put, and delete requests very easily.

If you want to see what route I should use for what method then simply fire php artisan route:list from commandline.

And because of laravel comes with built in csrf token verification middleware, you must have to pass _token with your post data request. Or either you can access those routes without csrf token verification by doing this:

Go to kernel.php in Http folder under the app directory, and comment the csrfToken line.

protected $middleware = [
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'Illuminate\View\Middleware\ShareErrorsFromSession',
 // 'App\Http\Middleware\VerifyCsrfToken',
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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