简体   繁体   中英

Lumen route groups error: “Undefined variable: app”

I just created a new lumen application with this very simple routes file:

<?php

$app->get('/', function () {
  return 'Hello World';
});


$app->group(['prefix' => '/admin'], function () {

  $app->get('/user', function () {
    return 'Admin user';
  });

});

And I get this error:

lumen.ERROR: exception 'ErrorException' with message 'Undefined variable: app' in /path/to/my/lumen/project/app/Http/routes.php:10

What's wrong?

Note that if I remove the route group everything works great.

The problem is the closure you're using in the group call:

$app->group(['prefix' => '/admin'], function () {

        $app->get('/user', function () {
        return 'Admin - user';
    });

});

You'll have to pass it a reference to $app :

$app->group(['prefix' => '/admin'], function () use ($app) {

        $app->get('/user', function () {
        return 'Admin - user';
    });

});

The lumen docs on the laravel website contained an error, but the docs on github have been fixed. As it turns out, the application instance is passed as an argument to the callback, so you can do away with that use ($app) bit, and instead write this:

$app->group(['prefix' => '/admin'], function ($app) {

        $app->get('/user', function () {
        return 'Admin - user';
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM