1
votes

When I remove the inital use Illuminate\Http\Request and add use App\Item instead in the Controller file, the items/create route responds with a 404. How can I still use the App\Item namespace and get to the items/create route? I've tried adding both, but does not work.

web.php

Route::get('items', 'ItemsController@index');
Route::get('items/{item}', 'ItemsController@show');
Route::get('items/create', 'ItemsController@create');

ItemsController.php

<?php

namespace App\Http\Controllers;

use App\Item;

class ItemsController extends Controller
{
    public function index(){
      $items = Item::all();
      return view('items.index', ['items' => $items]);
    }

    public function show(Item $item){
      return $item->body;
    }

    public function create(){
      return view('items.create');
    }
}

Item.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    //
}
2
Can you provide the code from the Item model? - Luis Deras
It is just a standard model, with nothing in it yet. I've added it, however. - K.G
So after a little more testing I found that the namespace in the Controller file may not be the issue, but maybe in the web.php file. I've deleted all routes and associated controller functions except for the items/create and it would go to the page. - K.G

2 Answers

3
votes

The problem is that laravel tries to match the routes in the order they are declared and the items/{item} route will match all routes starting with items/, including items/create. And because of the route model binding, Laravel tries to load an Item with ID create which obviously doesn't exist, so it throws a 404 error.

Route model binding in the docs:

Since the $user variable is type-hinted as the App\User Eloquent model and the variable name matches the {user} URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated.

To fix it simply change the order of your routes and put items/{item} after all other item/* routes:

Route::get('items', 'ItemsController@index');
Route::get('items/create', 'ItemsController@create');
Route::get('items/{item}', 'ItemsController@show');
0
votes

Can you try this, please.

<?php

namespace App\Http\Controllers;
use App\Item;
class ItemsController extends Controller
{
    public function index(){
      $items = Item::all();
      return view('items.index', ['items' => $items]);
    }

    public function show($id){
      $item= Item::find($id);
        return $item->body;
    }

    public function create(){
      return view('items.create');
    }
}