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
{
//
}
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 theApp\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');
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');
}
}