我向 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/