Home » Php » php – Laravel 5 POST routes to index instead of store

php – Laravel 5 POST routes to index instead of store

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am working on a Laravel 5 RESTful API that seems not to be routing the POST requests correctly.

This is my routes.php:

Route::group(array('prefix' => 'api/v1'), function()
{
    Route::resource('messages', 'IncomingMessages');
});

And this is my controller:

class IncomingMessages extends Controller
{   
    public function index() {
        return "This is index";
    }

    public function store() {
        return "This is store";
    }

    public function update() {
        return "This is update";
    }
}

And this is what happens:

  • Request GET mydomain.com/api/v1/messages/ –> This is index
  • Request PUT mydomain.com/api/v1/messages/1 –> This is update
  • Request POST mydomain.com/api/v1/messages/ –> This is index

This is what php artisan route:list returns:

  • GET|HEAD : api/v1/messages : api.v1.messages.index : App\Http\Controllers\[email protected]
  • GET|HEAD : api/v1/messages/create : api.v1.messages.create : App\Http\Controllers\[email protected]
  • POST : api/v1/messages : api.v1.messages.store : App\Http\Controllers\[email protected]
  • GET|HEAD : api/v1/messages/{messages} : api.v1.messages.show : App\Http\Controllers\[email protected]
  • GET|HEAD : api/v1/messages/{messages}/edit : api.v1.messages.edit : App\Http\Controllers\[email protected]
  • PUT : api/v1/messages/{messages} :api.v1.messages.update ; App\Http\Controllers\[email protected]
  • PATCH : api/v1/messages/{messages} : App\Http\Controllers\[email protected]
  • DELETE : api/v1/messages/{messages} : api.v1.messages.destroy : App\Http\Controllers\[email protected]

So, my question is:

What am I missing? Why is it routing to index() instead of routing to store()?

NOTES:

  • I have disabled “VerifyCsrfToken” in Kernel.php
  • I am trying the requests using Chromium plugin “Postman”.

UPDATE:

The problem was adding a trailing / to the URL. So, instead of using this URL:

mydomain.com/api/v1/messages/

I tried with this one:

mydomain.com/api/v1/messages

and it worked

How to&Answers:

The problem was caused by a trailing / being added to the URL. So, instead of using this URL:

mydomain.com/api/v1/messages/

I tried with this one:

mydomain.com/api/v1/messages

and it worked.

I discovered it by taking a look at the server’s log. That is how I discovered that POST requests to the URL messages/ were redirected.

Answer:

if you are still having this problem and the route is using FormRequest

check if there a authorize function in it because it will redirect if it returns false