Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel5 `RouteServiceProvider` `should be compatible with` Error

Tags:

php

laravel

I am developing a web application by Laravel5, and in code of Controller, I wrote a code bellow.

public function show($id)
{
    $post = Post::find($id);
    \View::share(compact('post'));
    return view('posts.show');
}

but, I want to write as follows.

public function show(Post $post)
{
    \View::share(compact('post'));
    return view('posts.show');
}

and in RouteServiceProvider.php, I added Router $router

public function boot(Router $router)
{

but, it doesn't work, and I got an error bellow.

Declaration of App\Providers\RouteServiceProvider::boot(App\Providers\Router $router) should be compatible with Illuminate\Foundation\Support\Providers\RouteServiceProvider::boot()

What is problem? Thanks!

like image 382
hiel Avatar asked Aug 12 '17 10:08

hiel


2 Answers

What laravel version do you use?

In version newer than 5.3, you have to write as follows.

public function boot()
{
    //
    parent::boot();
    Route::model('post', \App\Post::class);
}

Reference:

https://readouble.com/laravel/5.3/en/routing.html

https://readouble.com/laravel/5.2/en/routing.html

Explicit Binding section.

like image 180
Yujiro Avatar answered Sep 18 '22 15:09

Yujiro


boot method is inherited from Illuminate\Foundation\Support\Providers\RouteServiceProvider which doesn't have the same signature as yours which is causing this error.

If you have to use the router inside boot method then use app() helper function to get the instance of the router.

public function boot()
{
    $router = app('router'); // Router Instance

    parent::boot();
}
like image 39
Zayn Ali Avatar answered Sep 17 '22 15:09

Zayn Ali