【问题标题】:laravel 4 view::share doesn´t worklaravel 4 view::share 不起作用
【发布时间】:2013-09-06 08:07:32
【问题描述】:

一旦用户登录,我想通过我的所有视图共享用户名。我直接在 imy routes.php 中尝试过:

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

但它不共享任何东西。我也尝试将其放在以下路线中:

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

你能帮帮我吗?

编辑:

我在我需要的每个刀片中都使用了它:

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

但我想为我的所有观点定义一次 - 有人可以给我提示吗?

【问题讨论】:

  • 您是否将此用户名放置在每个页面的不同位置,如果不是,则只需在主布局中执行一次。即使你不能抓住变量并在你的主布局中分配它(你正在使用布局对吗?)

标签: php authentication view laravel share


【解决方案1】:

您可以创建一个路由过滤器,将用户名共享给视图。现在您可以将此过滤器应用到每个路由或路由组以在您的视图中使用它。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 2015-05-07
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多