php - 让一个变量可以在 Laravel 应用程序的任何地方访问

标签 php laravel laravel-5 laravel-5.1

我向 API 发出 cURL 请求

http://site/user


我收到了这个回复

    data: Object
    first_name: "Bob"
    last_name: "Jones"

我抓取名字和姓氏并将它们连接在一起并存储到变量调用 $name 中。

$fn = VSE::user('first_name',$username);
$ln = VSE::user('last_name',$username);
$name = ucwords($fn.' '.$ln); // Bob Jones

我想在我的导航中显示此 $name

在每个 View 中发送这个 $name 变量有点过头了。 我正在寻找一种更好的方法来做到这一点。

我应该怎么做才能在我的应用程序路由/ View 中访问该变量?


限制: 我无权访问 Auth::user 对象。

最佳答案

使用 View 编辑器使您需要的变量在每个 View 中可用。

View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

http://laravel.com/docs/5.1/views#view-composers

view()->composer('*', function ($view) {
    $fn = VSE::user('first_name',$username);
    $ln = VSE::user('last_name',$username);
    $name = ucwords($fn.' '.$ln); // Bob Jones

    $view->with('name', $name);
});

如果您不想使用 View 编辑器,您可以简单地在 AppServiceProvider 启动方法中添加对 view()->share() 方法的调用

public function boot()
{
    $fn = VSE::user('first_name',$username);
    $ln = VSE::user('last_name',$username);
    $name = ucwords($fn.' '.$ln); // Bob Jones

    view()->share('name', $name);
}

关于php - 让一个变量可以在 Laravel 应用程序的任何地方访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33418925/

相关文章:

php - 有什么解决方案可以在 laravel Blade 上操作 MySQL 数据库中包含的超链接吗?

php - 从 Laravel 5 中的动态表单将多行保存到数据库

php - 提交 PHP - HTML DATE 到 MySQL DATE

php - 非线性数据库检索

php - WooCommerce:检查商品是否已在购物车中

laravel - 在SSH Laravel 5.2中运行工匠代码

php - Laravel 如何自动获取数组 id

php - zend 框架表单输入在服务器上无法正常工作

laravel - 覆盖 Laravel 5.8 中的默认 Auth 路由

JavaScript 在验证后切换模式显示