dongmale0656 2017-07-08 19:40 采纳率: 100%
浏览 242
已采纳

路由Laravel命名空间问题

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条回答 默认 最新

  • dongxiao_0528 2017-07-09 01:06
    关注

    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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部