Andrea
Andrea

Reputation: 16590

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.

Upvotes: 0

Views: 2946

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76408

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';
    });
});

Upvotes: 3

Related Questions