dongmale0656 2017-07-09 03: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 09: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条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献