RouteServiceProvider找不到查询

时间:2017-03-07 14:33:30

标签: php laravel laravel-5 laravel-5.4

我正在尝试使用帖子制作seo友好的网址。所以到目前为止我所做的是RouteServiceProvider

namespace App\Providers;

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use App\Post;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {

        parent::boot();

        Route::bind('post', function($slug){ 
            return Post::published()->where('slug')->first();
        });
    }

这在我的BlogController中

public function show(Post $post){

    return view("blog.show", compact('post'));
}

当我去帖子http://example.com/slug-from-database时,我收到了错误

  

Builder.php第426行中的ModelNotFoundException:

     

没有模型[App \ Post]的查询结果。

为什么我收到此错误的任何想法?

1 个答案:

答案 0 :(得分:3)

您的$slug子句中缺少WHERE,此处为:

Route::bind('post', function($slug){ 
    return Post::published()->where('slug')->first();
});

像这样更改查询,它将起作用:

Post::published()->where('slug', $slug)->first();