Home » Php » Laravel NotFoundHttpException although route exists

Laravel NotFoundHttpException although route exists

Posted by: admin November 30, 2017 Leave a comment

Questions:

I use vue.js and Laravel 5.1 to create a little file sharing application.

Everything works perfect but now I wanted to make sure the owner of each file is able to remove users from his file (he had to share the file with those users at first of course), therefore I make a PUT request to an URL called /files/share.

My Laravel route looks like this:

Route::put('/files/share', '[email protected]');

When I run php artisan route:list it gets listed as well.

The client-side code looks like this:

this.$http.put('/files/share', { some_data }, function(data) {
    if(data.error){
        this.$set('error', data.error);
    } else {
        this.$set('file', data);
    }
});

The exact error that I get is this:

2/2 NotFoundHttpException in Handler.php line 46:
No query results for model [App\File].
1/2 ModelNotFoundException in Builder.php line 129:
No query results for model [App\File].

But the Application doesn’t even get to the controller, if I just return something from there the error is the same.

Answers:

With Laravel routes, the order matters. Routes with dynamic segments like files/{file} or resource routes should always be defined after the ones that are static. Otherwise Laravel will interpret the share part in your URL as ID.

So, as you’ve figured out yourself you simply need to change the order of your routes:

Route::put('/files/share', '[email protected]');
Route::resource('/files', 'FileController');

Questions:
Answers:

Thanks to lukasgeiter I checked my routes once more and had to define the /files/share route before my RESTful resource route.