Search code examples
slim

Slim PHP access object in route group


hello I want to create an object that can be used inside all the nested routes

use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;

return function (App $app) {

    $app->group('/api', function (App $app) {

        $this->user = \User::findOrFail(1);

        $app->get('/profile', function ($request, $response, $args) {
            var_dump($this->user);
        });

    });
};

the error I´m getting is

Type: Slim\Exception\ContainerValueNotFoundException
Message: Identifier "user" is not defined.

Solution

  • for that you should use a container

    $app = new \Slim\App();
    $container = $app->getContainer();
    $container['user'] = function () {
        //code
    };