0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

php artisan config:cacheでCannot redeclareエラー

Posted at

ある日、php artisan config:cacheを叩くとこんなエラーが発生しました。

$ php artisan route:cache
Route cache cleared!
PHP Fatal error:  Cannot redeclare defaultRoutes() (previously declared in /app/hogehoge/app/Http/routes.php:35) in ...

エラーの内容を見ていると、defaultRoutes()が再定義されているよ!というものでした。
このdefaultRoutes()というのは、routes.phpで定義してる基本的なルーティングの設定をまとめたメソッドになっています。

具体的には、下記のようにルーティングが記述されていました。
※一部省略しています

/app/Http/routes.php
if (strpos(url(), config('app.test_domain'))) {
    Route::group(['middleware' => 'auth'], function () {
        defaultRoutes();
    });
} else {
    defaultRoutes();
}
/*
 * 通常のrouteを定義
 */
function defaultRoutes ()
{
    Route::get('/hogehoge', 'HogeController@index');
}

この処理では、テストドメインでアクセスした際はBASIC認証を掛け、それ以外のドメインのアクセスの際には、BASIC認証を掛けずにページにアクセスできるようにしています。

通常のルートをdefaultRoutes()で定義して、それを呼び出すような処理にしていました。

もちろん、この書き方で正しくルーティングされており、実際にページにアクセスしてもエラーが出ることはありませんでした。

しかし、このままだとphp artisan config:cachephp artisan route:cacheを叩こうとすると、タイトルのようなエラーが出てしまうようです。

この問題は、クロージャーを使用するように修正することで解決できました :muscle:
php - Cannot redeclare Laravel routes method duplication on phpunit - Stack Overflow

/app/Http/routes.php
/*
 * 通常のrouteを定義
 */
$defaultRoutes = function(){
    Route::get('/hogehoge', 'HogeController@index');
};

if (strpos(url(), config('app.test_domain'))) {
    Route::group(['middleware' => 'auth'], $defaultRoutes);
} else {
    $defaultRoutes();
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?