Gweit
Gweit

Reputation: 1

laravel 4 view::share doesn´t work

I would like to share the username through all my views once the user is logged in. I tried this direct in imy routes.php:

View::share('user', $user);

but it doesn´t share anything. I tried also to put it in the following route:

Route::post('auth', function()
{

    $user = Input::get('username');

    View::share('user', $user);

    $credentials = array(
    'username' => Input::get('username'),
    'password' => Input::get('password')
    );

if (Auth::attempt($credentials))
{
    //Cache::put('user', $user);
    return View::make('panel')->with('user', $user);
}
//return 'user :' .$user. ' and pass : ' .$pass;
return Redirect::to('/');
});

Could you please help me out?

EDIT:

i solved using this in every blade i need it:

$user = Auth::user()->username;

but i would like to define it once for all my views - can somebody give me a tip?

Upvotes: 0

Views: 263

Answers (1)

r15ch13
r15ch13

Reputation: 337

You could create a route filter which shares the username to the view. Now you can apply this filter to every route, or route group to use it in your views.

Route::filter('shared.user', function()
{
    $user = '';
    if(Auth::check())
    {
        $user = Auth::user()->username;
    }
    View::share('user', $user);
});

Route::get('hello', array('before' => 'shared.user', function()
{
    return View::make('hello');
}));

Route::group(array('before' => 'shared.user'), function()
{
    // routes which show the username
});

Upvotes: 1

Related Questions