Reputation: 12470
In my Laravel 4 project I've bound the current user to the views using the share()
method like so:
View::share(['currentUser' => Sentry::getUser()]);
This works when browsing the site, all the views have access to the variable $currentUser
. However, when attempting to test my application, the variable is never bound, despite a user definitely being logged in.
class PagesControllerTest extends TestCase
{
public function setUp()
{
parent::setUp();
// This works, as halting the application and dumping the user manually demonstrate it as such.
Sentry::login(User::first());
}
public function testIndex()
{
$this->get('/');
$this->assertResponseOk();
}
}
However, this simply results in a stack-trace of errors...
ErrorException: Trying to get property of non-object (View: ~/Sites/laravel/app/views/layouts/application.blade.php) (View: ~/Sites/laravel/app/views/layouts/application.blade.php)
...
Caused by
ErrorException: Trying to get property of non-object (View: ~/Sites/laravel/app/views/layouts/application.blade.php)
...
Caused by
ErrorException: Trying to get property of non-object
The exact line this fails at is where the view tries to access the $currentUser
variable.
If I use a view composer instead, like follows, it solves the problem in this instance - but I want the variable available in ALL views, not just the ones I specify, and I'd also like to know WHY this is occurring.
View::composer('layouts.application', function($view)
{
$view->with('currentUser', Sentry::currentUser());
});
Upvotes: 0
Views: 1029
Reputation: 8029
I'm guessing you are doing View::share
in app/start/global.php. This file is invoked by calling parent::setUp()
, which is before you've done Sentry::login
, and thus, $currentUser
will be null. You should either find a way to delay the View::share
(using a view composer is one way to do this) or just use Sentry::getUser()
in your views.
Upvotes: 2